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