xref: /openbmc/linux/drivers/xen/gntdev.c (revision c059ee9d)
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);
400 		pr_debug("unmap handle=%d st=%d\n",
401 			map->unmap_ops[offset+i].handle,
402 			map->unmap_ops[offset+i].status);
403 		map->unmap_ops[offset+i].handle = INVALID_GRANT_HANDLE;
404 		if (use_ptemod) {
405 			WARN_ON(map->kunmap_ops[offset+i].status);
406 			pr_debug("kunmap handle=%u st=%d\n",
407 				 map->kunmap_ops[offset+i].handle,
408 				 map->kunmap_ops[offset+i].status);
409 			map->kunmap_ops[offset+i].handle = INVALID_GRANT_HANDLE;
410 		}
411 	}
412 	/*
413 	 * Decrease the live-grant counter.  This must happen after the loop to
414 	 * prevent premature reuse of the grants by gnttab_mmap().
415 	 */
416 	atomic_sub(data->count, &map->live_grants);
417 
418 	/* Release reference taken by __unmap_grant_pages */
419 	gntdev_put_map(NULL, map);
420 }
421 
422 static void __unmap_grant_pages(struct gntdev_grant_map *map, int offset,
423 			       int pages)
424 {
425 	if (map->notify.flags & UNMAP_NOTIFY_CLEAR_BYTE) {
426 		int pgno = (map->notify.addr >> PAGE_SHIFT);
427 
428 		if (pgno >= offset && pgno < offset + pages) {
429 			/* No need for kmap, pages are in lowmem */
430 			uint8_t *tmp = pfn_to_kaddr(page_to_pfn(map->pages[pgno]));
431 
432 			tmp[map->notify.addr & (PAGE_SIZE-1)] = 0;
433 			map->notify.flags &= ~UNMAP_NOTIFY_CLEAR_BYTE;
434 		}
435 	}
436 
437 	map->unmap_data.unmap_ops = map->unmap_ops + offset;
438 	map->unmap_data.kunmap_ops = use_ptemod ? map->kunmap_ops + offset : NULL;
439 	map->unmap_data.pages = map->pages + offset;
440 	map->unmap_data.count = pages;
441 	map->unmap_data.done = __unmap_grant_pages_done;
442 	map->unmap_data.data = map;
443 	refcount_inc(&map->users); /* to keep map alive during async call below */
444 
445 	gnttab_unmap_refs_async(&map->unmap_data);
446 }
447 
448 static void unmap_grant_pages(struct gntdev_grant_map *map, int offset,
449 			      int pages)
450 {
451 	int range;
452 
453 	if (atomic_read(&map->live_grants) == 0)
454 		return; /* Nothing to do */
455 
456 	pr_debug("unmap %d+%d [%d+%d]\n", map->index, map->count, offset, pages);
457 
458 	/* It is possible the requested range will have a "hole" where we
459 	 * already unmapped some of the grants. Only unmap valid ranges.
460 	 */
461 	while (pages) {
462 		while (pages && map->being_removed[offset]) {
463 			offset++;
464 			pages--;
465 		}
466 		range = 0;
467 		while (range < pages) {
468 			if (map->being_removed[offset + range])
469 				break;
470 			map->being_removed[offset + range] = true;
471 			range++;
472 		}
473 		if (range)
474 			__unmap_grant_pages(map, offset, range);
475 		offset += range;
476 		pages -= range;
477 	}
478 }
479 
480 /* ------------------------------------------------------------------ */
481 
482 static void gntdev_vma_open(struct vm_area_struct *vma)
483 {
484 	struct gntdev_grant_map *map = vma->vm_private_data;
485 
486 	pr_debug("gntdev_vma_open %p\n", vma);
487 	refcount_inc(&map->users);
488 }
489 
490 static void gntdev_vma_close(struct vm_area_struct *vma)
491 {
492 	struct gntdev_grant_map *map = vma->vm_private_data;
493 	struct file *file = vma->vm_file;
494 	struct gntdev_priv *priv = file->private_data;
495 
496 	pr_debug("gntdev_vma_close %p\n", vma);
497 	if (use_ptemod) {
498 		WARN_ON(map->vma != vma);
499 		mmu_interval_notifier_remove(&map->notifier);
500 		map->vma = NULL;
501 	}
502 	vma->vm_private_data = NULL;
503 	gntdev_put_map(priv, map);
504 }
505 
506 static struct page *gntdev_vma_find_special_page(struct vm_area_struct *vma,
507 						 unsigned long addr)
508 {
509 	struct gntdev_grant_map *map = vma->vm_private_data;
510 
511 	return map->pages[(addr - map->pages_vm_start) >> PAGE_SHIFT];
512 }
513 
514 static const struct vm_operations_struct gntdev_vmops = {
515 	.open = gntdev_vma_open,
516 	.close = gntdev_vma_close,
517 	.find_special_page = gntdev_vma_find_special_page,
518 };
519 
520 /* ------------------------------------------------------------------ */
521 
522 static bool gntdev_invalidate(struct mmu_interval_notifier *mn,
523 			      const struct mmu_notifier_range *range,
524 			      unsigned long cur_seq)
525 {
526 	struct gntdev_grant_map *map =
527 		container_of(mn, struct gntdev_grant_map, notifier);
528 	unsigned long mstart, mend;
529 
530 	if (!mmu_notifier_range_blockable(range))
531 		return false;
532 
533 	/*
534 	 * If the VMA is split or otherwise changed the notifier is not
535 	 * updated, but we don't want to process VA's outside the modified
536 	 * VMA. FIXME: It would be much more understandable to just prevent
537 	 * modifying the VMA in the first place.
538 	 */
539 	if (map->vma->vm_start >= range->end ||
540 	    map->vma->vm_end <= range->start)
541 		return true;
542 
543 	mstart = max(range->start, map->vma->vm_start);
544 	mend = min(range->end, map->vma->vm_end);
545 	pr_debug("map %d+%d (%lx %lx), range %lx %lx, mrange %lx %lx\n",
546 			map->index, map->count,
547 			map->vma->vm_start, map->vma->vm_end,
548 			range->start, range->end, mstart, mend);
549 	unmap_grant_pages(map,
550 				(mstart - map->vma->vm_start) >> PAGE_SHIFT,
551 				(mend - mstart) >> PAGE_SHIFT);
552 
553 	return true;
554 }
555 
556 static const struct mmu_interval_notifier_ops gntdev_mmu_ops = {
557 	.invalidate = gntdev_invalidate,
558 };
559 
560 /* ------------------------------------------------------------------ */
561 
562 static int gntdev_open(struct inode *inode, struct file *flip)
563 {
564 	struct gntdev_priv *priv;
565 
566 	priv = kzalloc(sizeof(*priv), GFP_KERNEL);
567 	if (!priv)
568 		return -ENOMEM;
569 
570 	INIT_LIST_HEAD(&priv->maps);
571 	mutex_init(&priv->lock);
572 
573 #ifdef CONFIG_XEN_GNTDEV_DMABUF
574 	priv->dmabuf_priv = gntdev_dmabuf_init(flip);
575 	if (IS_ERR(priv->dmabuf_priv)) {
576 		int ret = PTR_ERR(priv->dmabuf_priv);
577 
578 		kfree(priv);
579 		return ret;
580 	}
581 #endif
582 
583 	flip->private_data = priv;
584 #ifdef CONFIG_XEN_GRANT_DMA_ALLOC
585 	priv->dma_dev = gntdev_miscdev.this_device;
586 	dma_coerce_mask_and_coherent(priv->dma_dev, DMA_BIT_MASK(64));
587 #endif
588 	pr_debug("priv %p\n", priv);
589 
590 	return 0;
591 }
592 
593 static int gntdev_release(struct inode *inode, struct file *flip)
594 {
595 	struct gntdev_priv *priv = flip->private_data;
596 	struct gntdev_grant_map *map;
597 
598 	pr_debug("priv %p\n", priv);
599 
600 	mutex_lock(&priv->lock);
601 	while (!list_empty(&priv->maps)) {
602 		map = list_entry(priv->maps.next,
603 				 struct gntdev_grant_map, next);
604 		list_del(&map->next);
605 		gntdev_put_map(NULL /* already removed */, map);
606 	}
607 	mutex_unlock(&priv->lock);
608 
609 #ifdef CONFIG_XEN_GNTDEV_DMABUF
610 	gntdev_dmabuf_fini(priv->dmabuf_priv);
611 #endif
612 
613 	kfree(priv);
614 	return 0;
615 }
616 
617 static long gntdev_ioctl_map_grant_ref(struct gntdev_priv *priv,
618 				       struct ioctl_gntdev_map_grant_ref __user *u)
619 {
620 	struct ioctl_gntdev_map_grant_ref op;
621 	struct gntdev_grant_map *map;
622 	int err;
623 
624 	if (copy_from_user(&op, u, sizeof(op)) != 0)
625 		return -EFAULT;
626 	pr_debug("priv %p, add %d\n", priv, op.count);
627 	if (unlikely(gntdev_test_page_count(op.count)))
628 		return -EINVAL;
629 
630 	err = -ENOMEM;
631 	map = gntdev_alloc_map(priv, op.count, 0 /* This is not a dma-buf. */);
632 	if (!map)
633 		return err;
634 
635 	if (copy_from_user(map->grants, &u->refs,
636 			   sizeof(map->grants[0]) * op.count) != 0) {
637 		gntdev_put_map(NULL, map);
638 		return -EFAULT;
639 	}
640 
641 	mutex_lock(&priv->lock);
642 	gntdev_add_map(priv, map);
643 	op.index = map->index << PAGE_SHIFT;
644 	mutex_unlock(&priv->lock);
645 
646 	if (copy_to_user(u, &op, sizeof(op)) != 0)
647 		return -EFAULT;
648 
649 	return 0;
650 }
651 
652 static long gntdev_ioctl_unmap_grant_ref(struct gntdev_priv *priv,
653 					 struct ioctl_gntdev_unmap_grant_ref __user *u)
654 {
655 	struct ioctl_gntdev_unmap_grant_ref op;
656 	struct gntdev_grant_map *map;
657 	int err = -ENOENT;
658 
659 	if (copy_from_user(&op, u, sizeof(op)) != 0)
660 		return -EFAULT;
661 	pr_debug("priv %p, del %d+%d\n", priv, (int)op.index, (int)op.count);
662 
663 	mutex_lock(&priv->lock);
664 	map = gntdev_find_map_index(priv, op.index >> PAGE_SHIFT, op.count);
665 	if (map) {
666 		list_del(&map->next);
667 		err = 0;
668 	}
669 	mutex_unlock(&priv->lock);
670 	if (map)
671 		gntdev_put_map(priv, map);
672 	return err;
673 }
674 
675 static long gntdev_ioctl_get_offset_for_vaddr(struct gntdev_priv *priv,
676 					      struct ioctl_gntdev_get_offset_for_vaddr __user *u)
677 {
678 	struct ioctl_gntdev_get_offset_for_vaddr op;
679 	struct vm_area_struct *vma;
680 	struct gntdev_grant_map *map;
681 	int rv = -EINVAL;
682 
683 	if (copy_from_user(&op, u, sizeof(op)) != 0)
684 		return -EFAULT;
685 	pr_debug("priv %p, offset for vaddr %lx\n", priv, (unsigned long)op.vaddr);
686 
687 	mmap_read_lock(current->mm);
688 	vma = find_vma(current->mm, op.vaddr);
689 	if (!vma || vma->vm_ops != &gntdev_vmops)
690 		goto out_unlock;
691 
692 	map = vma->vm_private_data;
693 	if (!map)
694 		goto out_unlock;
695 
696 	op.offset = map->index << PAGE_SHIFT;
697 	op.count = map->count;
698 	rv = 0;
699 
700  out_unlock:
701 	mmap_read_unlock(current->mm);
702 
703 	if (rv == 0 && copy_to_user(u, &op, sizeof(op)) != 0)
704 		return -EFAULT;
705 	return rv;
706 }
707 
708 static long gntdev_ioctl_notify(struct gntdev_priv *priv, void __user *u)
709 {
710 	struct ioctl_gntdev_unmap_notify op;
711 	struct gntdev_grant_map *map;
712 	int rc;
713 	int out_flags;
714 	evtchn_port_t out_event;
715 
716 	if (copy_from_user(&op, u, sizeof(op)))
717 		return -EFAULT;
718 
719 	if (op.action & ~(UNMAP_NOTIFY_CLEAR_BYTE|UNMAP_NOTIFY_SEND_EVENT))
720 		return -EINVAL;
721 
722 	/* We need to grab a reference to the event channel we are going to use
723 	 * to send the notify before releasing the reference we may already have
724 	 * (if someone has called this ioctl twice). This is required so that
725 	 * it is possible to change the clear_byte part of the notification
726 	 * without disturbing the event channel part, which may now be the last
727 	 * reference to that event channel.
728 	 */
729 	if (op.action & UNMAP_NOTIFY_SEND_EVENT) {
730 		if (evtchn_get(op.event_channel_port))
731 			return -EINVAL;
732 	}
733 
734 	out_flags = op.action;
735 	out_event = op.event_channel_port;
736 
737 	mutex_lock(&priv->lock);
738 
739 	list_for_each_entry(map, &priv->maps, next) {
740 		uint64_t begin = map->index << PAGE_SHIFT;
741 		uint64_t end = (map->index + map->count) << PAGE_SHIFT;
742 		if (op.index >= begin && op.index < end)
743 			goto found;
744 	}
745 	rc = -ENOENT;
746 	goto unlock_out;
747 
748  found:
749 	if ((op.action & UNMAP_NOTIFY_CLEAR_BYTE) &&
750 			(map->flags & GNTMAP_readonly)) {
751 		rc = -EINVAL;
752 		goto unlock_out;
753 	}
754 
755 	out_flags = map->notify.flags;
756 	out_event = map->notify.event;
757 
758 	map->notify.flags = op.action;
759 	map->notify.addr = op.index - (map->index << PAGE_SHIFT);
760 	map->notify.event = op.event_channel_port;
761 
762 	rc = 0;
763 
764  unlock_out:
765 	mutex_unlock(&priv->lock);
766 
767 	/* Drop the reference to the event channel we did not save in the map */
768 	if (out_flags & UNMAP_NOTIFY_SEND_EVENT)
769 		evtchn_put(out_event);
770 
771 	return rc;
772 }
773 
774 #define GNTDEV_COPY_BATCH 16
775 
776 struct gntdev_copy_batch {
777 	struct gnttab_copy ops[GNTDEV_COPY_BATCH];
778 	struct page *pages[GNTDEV_COPY_BATCH];
779 	s16 __user *status[GNTDEV_COPY_BATCH];
780 	unsigned int nr_ops;
781 	unsigned int nr_pages;
782 	bool writeable;
783 };
784 
785 static int gntdev_get_page(struct gntdev_copy_batch *batch, void __user *virt,
786 				unsigned long *gfn)
787 {
788 	unsigned long addr = (unsigned long)virt;
789 	struct page *page;
790 	unsigned long xen_pfn;
791 	int ret;
792 
793 	ret = pin_user_pages_fast(addr, 1, batch->writeable ? FOLL_WRITE : 0, &page);
794 	if (ret < 0)
795 		return ret;
796 
797 	batch->pages[batch->nr_pages++] = page;
798 
799 	xen_pfn = page_to_xen_pfn(page) + XEN_PFN_DOWN(addr & ~PAGE_MASK);
800 	*gfn = pfn_to_gfn(xen_pfn);
801 
802 	return 0;
803 }
804 
805 static void gntdev_put_pages(struct gntdev_copy_batch *batch)
806 {
807 	unpin_user_pages_dirty_lock(batch->pages, batch->nr_pages, batch->writeable);
808 	batch->nr_pages = 0;
809 	batch->writeable = false;
810 }
811 
812 static int gntdev_copy(struct gntdev_copy_batch *batch)
813 {
814 	unsigned int i;
815 
816 	gnttab_batch_copy(batch->ops, batch->nr_ops);
817 	gntdev_put_pages(batch);
818 
819 	/*
820 	 * For each completed op, update the status if the op failed
821 	 * and all previous ops for the segment were successful.
822 	 */
823 	for (i = 0; i < batch->nr_ops; i++) {
824 		s16 status = batch->ops[i].status;
825 		s16 old_status;
826 
827 		if (status == GNTST_okay)
828 			continue;
829 
830 		if (__get_user(old_status, batch->status[i]))
831 			return -EFAULT;
832 
833 		if (old_status != GNTST_okay)
834 			continue;
835 
836 		if (__put_user(status, batch->status[i]))
837 			return -EFAULT;
838 	}
839 
840 	batch->nr_ops = 0;
841 	return 0;
842 }
843 
844 static int gntdev_grant_copy_seg(struct gntdev_copy_batch *batch,
845 				 struct gntdev_grant_copy_segment *seg,
846 				 s16 __user *status)
847 {
848 	uint16_t copied = 0;
849 
850 	/*
851 	 * Disallow local -> local copies since there is only space in
852 	 * batch->pages for one page per-op and this would be a very
853 	 * expensive memcpy().
854 	 */
855 	if (!(seg->flags & (GNTCOPY_source_gref | GNTCOPY_dest_gref)))
856 		return -EINVAL;
857 
858 	/* Can't cross page if source/dest is a grant ref. */
859 	if (seg->flags & GNTCOPY_source_gref) {
860 		if (seg->source.foreign.offset + seg->len > XEN_PAGE_SIZE)
861 			return -EINVAL;
862 	}
863 	if (seg->flags & GNTCOPY_dest_gref) {
864 		if (seg->dest.foreign.offset + seg->len > XEN_PAGE_SIZE)
865 			return -EINVAL;
866 	}
867 
868 	if (put_user(GNTST_okay, status))
869 		return -EFAULT;
870 
871 	while (copied < seg->len) {
872 		struct gnttab_copy *op;
873 		void __user *virt;
874 		size_t len, off;
875 		unsigned long gfn;
876 		int ret;
877 
878 		if (batch->nr_ops >= GNTDEV_COPY_BATCH) {
879 			ret = gntdev_copy(batch);
880 			if (ret < 0)
881 				return ret;
882 		}
883 
884 		len = seg->len - copied;
885 
886 		op = &batch->ops[batch->nr_ops];
887 		op->flags = 0;
888 
889 		if (seg->flags & GNTCOPY_source_gref) {
890 			op->source.u.ref = seg->source.foreign.ref;
891 			op->source.domid = seg->source.foreign.domid;
892 			op->source.offset = seg->source.foreign.offset + copied;
893 			op->flags |= GNTCOPY_source_gref;
894 		} else {
895 			virt = seg->source.virt + copied;
896 			off = (unsigned long)virt & ~XEN_PAGE_MASK;
897 			len = min(len, (size_t)XEN_PAGE_SIZE - off);
898 			batch->writeable = false;
899 
900 			ret = gntdev_get_page(batch, virt, &gfn);
901 			if (ret < 0)
902 				return ret;
903 
904 			op->source.u.gmfn = gfn;
905 			op->source.domid = DOMID_SELF;
906 			op->source.offset = off;
907 		}
908 
909 		if (seg->flags & GNTCOPY_dest_gref) {
910 			op->dest.u.ref = seg->dest.foreign.ref;
911 			op->dest.domid = seg->dest.foreign.domid;
912 			op->dest.offset = seg->dest.foreign.offset + copied;
913 			op->flags |= GNTCOPY_dest_gref;
914 		} else {
915 			virt = seg->dest.virt + copied;
916 			off = (unsigned long)virt & ~XEN_PAGE_MASK;
917 			len = min(len, (size_t)XEN_PAGE_SIZE - off);
918 			batch->writeable = true;
919 
920 			ret = gntdev_get_page(batch, virt, &gfn);
921 			if (ret < 0)
922 				return ret;
923 
924 			op->dest.u.gmfn = gfn;
925 			op->dest.domid = DOMID_SELF;
926 			op->dest.offset = off;
927 		}
928 
929 		op->len = len;
930 		copied += len;
931 
932 		batch->status[batch->nr_ops] = status;
933 		batch->nr_ops++;
934 	}
935 
936 	return 0;
937 }
938 
939 static long gntdev_ioctl_grant_copy(struct gntdev_priv *priv, void __user *u)
940 {
941 	struct ioctl_gntdev_grant_copy copy;
942 	struct gntdev_copy_batch batch;
943 	unsigned int i;
944 	int ret = 0;
945 
946 	if (copy_from_user(&copy, u, sizeof(copy)))
947 		return -EFAULT;
948 
949 	batch.nr_ops = 0;
950 	batch.nr_pages = 0;
951 
952 	for (i = 0; i < copy.count; i++) {
953 		struct gntdev_grant_copy_segment seg;
954 
955 		if (copy_from_user(&seg, &copy.segments[i], sizeof(seg))) {
956 			ret = -EFAULT;
957 			goto out;
958 		}
959 
960 		ret = gntdev_grant_copy_seg(&batch, &seg, &copy.segments[i].status);
961 		if (ret < 0)
962 			goto out;
963 
964 		cond_resched();
965 	}
966 	if (batch.nr_ops)
967 		ret = gntdev_copy(&batch);
968 	return ret;
969 
970   out:
971 	gntdev_put_pages(&batch);
972 	return ret;
973 }
974 
975 static long gntdev_ioctl(struct file *flip,
976 			 unsigned int cmd, unsigned long arg)
977 {
978 	struct gntdev_priv *priv = flip->private_data;
979 	void __user *ptr = (void __user *)arg;
980 
981 	switch (cmd) {
982 	case IOCTL_GNTDEV_MAP_GRANT_REF:
983 		return gntdev_ioctl_map_grant_ref(priv, ptr);
984 
985 	case IOCTL_GNTDEV_UNMAP_GRANT_REF:
986 		return gntdev_ioctl_unmap_grant_ref(priv, ptr);
987 
988 	case IOCTL_GNTDEV_GET_OFFSET_FOR_VADDR:
989 		return gntdev_ioctl_get_offset_for_vaddr(priv, ptr);
990 
991 	case IOCTL_GNTDEV_SET_UNMAP_NOTIFY:
992 		return gntdev_ioctl_notify(priv, ptr);
993 
994 	case IOCTL_GNTDEV_GRANT_COPY:
995 		return gntdev_ioctl_grant_copy(priv, ptr);
996 
997 #ifdef CONFIG_XEN_GNTDEV_DMABUF
998 	case IOCTL_GNTDEV_DMABUF_EXP_FROM_REFS:
999 		return gntdev_ioctl_dmabuf_exp_from_refs(priv, use_ptemod, ptr);
1000 
1001 	case IOCTL_GNTDEV_DMABUF_EXP_WAIT_RELEASED:
1002 		return gntdev_ioctl_dmabuf_exp_wait_released(priv, ptr);
1003 
1004 	case IOCTL_GNTDEV_DMABUF_IMP_TO_REFS:
1005 		return gntdev_ioctl_dmabuf_imp_to_refs(priv, ptr);
1006 
1007 	case IOCTL_GNTDEV_DMABUF_IMP_RELEASE:
1008 		return gntdev_ioctl_dmabuf_imp_release(priv, ptr);
1009 #endif
1010 
1011 	default:
1012 		pr_debug("priv %p, unknown cmd %x\n", priv, cmd);
1013 		return -ENOIOCTLCMD;
1014 	}
1015 
1016 	return 0;
1017 }
1018 
1019 static int gntdev_mmap(struct file *flip, struct vm_area_struct *vma)
1020 {
1021 	struct gntdev_priv *priv = flip->private_data;
1022 	int index = vma->vm_pgoff;
1023 	int count = vma_pages(vma);
1024 	struct gntdev_grant_map *map;
1025 	int err = -EINVAL;
1026 
1027 	if ((vma->vm_flags & VM_WRITE) && !(vma->vm_flags & VM_SHARED))
1028 		return -EINVAL;
1029 
1030 	pr_debug("map %d+%d at %lx (pgoff %lx)\n",
1031 			index, count, vma->vm_start, vma->vm_pgoff);
1032 
1033 	mutex_lock(&priv->lock);
1034 	map = gntdev_find_map_index(priv, index, count);
1035 	if (!map)
1036 		goto unlock_out;
1037 	if (use_ptemod && map->vma)
1038 		goto unlock_out;
1039 	if (atomic_read(&map->live_grants)) {
1040 		err = -EAGAIN;
1041 		goto unlock_out;
1042 	}
1043 	refcount_inc(&map->users);
1044 
1045 	vma->vm_ops = &gntdev_vmops;
1046 
1047 	vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP | VM_MIXEDMAP;
1048 
1049 	if (use_ptemod)
1050 		vma->vm_flags |= VM_DONTCOPY;
1051 
1052 	vma->vm_private_data = map;
1053 	if (map->flags) {
1054 		if ((vma->vm_flags & VM_WRITE) &&
1055 				(map->flags & GNTMAP_readonly))
1056 			goto out_unlock_put;
1057 	} else {
1058 		map->flags = GNTMAP_host_map;
1059 		if (!(vma->vm_flags & VM_WRITE))
1060 			map->flags |= GNTMAP_readonly;
1061 	}
1062 
1063 	if (use_ptemod) {
1064 		map->vma = vma;
1065 		err = mmu_interval_notifier_insert_locked(
1066 			&map->notifier, vma->vm_mm, vma->vm_start,
1067 			vma->vm_end - vma->vm_start, &gntdev_mmu_ops);
1068 		if (err) {
1069 			map->vma = NULL;
1070 			goto out_unlock_put;
1071 		}
1072 	}
1073 	mutex_unlock(&priv->lock);
1074 
1075 	if (use_ptemod) {
1076 		/*
1077 		 * gntdev takes the address of the PTE in find_grant_ptes() and
1078 		 * passes it to the hypervisor in gntdev_map_grant_pages(). The
1079 		 * purpose of the notifier is to prevent the hypervisor pointer
1080 		 * to the PTE from going stale.
1081 		 *
1082 		 * Since this vma's mappings can't be touched without the
1083 		 * mmap_lock, and we are holding it now, there is no need for
1084 		 * the notifier_range locking pattern.
1085 		 */
1086 		mmu_interval_read_begin(&map->notifier);
1087 
1088 		map->pages_vm_start = vma->vm_start;
1089 		err = apply_to_page_range(vma->vm_mm, vma->vm_start,
1090 					  vma->vm_end - vma->vm_start,
1091 					  find_grant_ptes, map);
1092 		if (err) {
1093 			pr_warn("find_grant_ptes() failure.\n");
1094 			goto out_put_map;
1095 		}
1096 	}
1097 
1098 	err = gntdev_map_grant_pages(map);
1099 	if (err)
1100 		goto out_put_map;
1101 
1102 	if (!use_ptemod) {
1103 		err = vm_map_pages_zero(vma, map->pages, map->count);
1104 		if (err)
1105 			goto out_put_map;
1106 	}
1107 
1108 	return 0;
1109 
1110 unlock_out:
1111 	mutex_unlock(&priv->lock);
1112 	return err;
1113 
1114 out_unlock_put:
1115 	mutex_unlock(&priv->lock);
1116 out_put_map:
1117 	if (use_ptemod) {
1118 		unmap_grant_pages(map, 0, map->count);
1119 		if (map->vma) {
1120 			mmu_interval_notifier_remove(&map->notifier);
1121 			map->vma = NULL;
1122 		}
1123 	}
1124 	gntdev_put_map(priv, map);
1125 	return err;
1126 }
1127 
1128 static const struct file_operations gntdev_fops = {
1129 	.owner = THIS_MODULE,
1130 	.open = gntdev_open,
1131 	.release = gntdev_release,
1132 	.mmap = gntdev_mmap,
1133 	.unlocked_ioctl = gntdev_ioctl
1134 };
1135 
1136 static struct miscdevice gntdev_miscdev = {
1137 	.minor        = MISC_DYNAMIC_MINOR,
1138 	.name         = "xen/gntdev",
1139 	.fops         = &gntdev_fops,
1140 };
1141 
1142 /* ------------------------------------------------------------------ */
1143 
1144 static int __init gntdev_init(void)
1145 {
1146 	int err;
1147 
1148 	if (!xen_domain())
1149 		return -ENODEV;
1150 
1151 	use_ptemod = !xen_feature(XENFEAT_auto_translated_physmap);
1152 
1153 	err = misc_register(&gntdev_miscdev);
1154 	if (err != 0) {
1155 		pr_err("Could not register gntdev device\n");
1156 		return err;
1157 	}
1158 	return 0;
1159 }
1160 
1161 static void __exit gntdev_exit(void)
1162 {
1163 	misc_deregister(&gntdev_miscdev);
1164 }
1165 
1166 module_init(gntdev_init);
1167 module_exit(gntdev_exit);
1168 
1169 /* ------------------------------------------------------------------ */
1170