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