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