• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * VFIO: IOMMU DMA mapping support for Type1 IOMMU
4  *
5  * Copyright (C) 2012 Red Hat, Inc.  All rights reserved.
6  *     Author: Alex Williamson <alex.williamson@redhat.com>
7  *
8  * Derived from original vfio:
9  * Copyright 2010 Cisco Systems, Inc.  All rights reserved.
10  * Author: Tom Lyon, pugs@cisco.com
11  *
12  * We arbitrarily define a Type1 IOMMU as one matching the below code.
13  * It could be called the x86 IOMMU as it's designed for AMD-Vi & Intel
14  * VT-d, but that makes it harder to re-use as theoretically anyone
15  * implementing a similar IOMMU could make use of this.  We expect the
16  * IOMMU to support the IOMMU API and have few to no restrictions around
17  * the IOVA range that can be mapped.  The Type1 IOMMU is currently
18  * optimized for relatively static mappings of a userspace process with
19  * userspace pages pinned into memory.  We also assume devices and IOMMU
20  * domains are PCI based as the IOMMU API is still centered around a
21  * device/bus interface rather than a group interface.
22  */
23 
24 #include <linux/compat.h>
25 #include <linux/device.h>
26 #include <linux/fs.h>
27 #include <linux/highmem.h>
28 #include <linux/iommu.h>
29 #include <linux/module.h>
30 #include <linux/mm.h>
31 #include <linux/kthread.h>
32 #include <linux/rbtree.h>
33 #include <linux/sched/signal.h>
34 #include <linux/sched/mm.h>
35 #include <linux/slab.h>
36 #include <linux/uaccess.h>
37 #include <linux/vfio.h>
38 #include <linux/workqueue.h>
39 #include <linux/notifier.h>
40 #include "vfio.h"
41 
42 #define DRIVER_VERSION  "0.2"
43 #define DRIVER_AUTHOR   "Alex Williamson <alex.williamson@redhat.com>"
44 #define DRIVER_DESC     "Type1 IOMMU driver for VFIO"
45 
46 static bool allow_unsafe_interrupts;
47 module_param_named(allow_unsafe_interrupts,
48 		   allow_unsafe_interrupts, bool, S_IRUGO | S_IWUSR);
49 MODULE_PARM_DESC(allow_unsafe_interrupts,
50 		 "Enable VFIO IOMMU support for on platforms without interrupt remapping support.");
51 
52 static bool disable_hugepages;
53 module_param_named(disable_hugepages,
54 		   disable_hugepages, bool, S_IRUGO | S_IWUSR);
55 MODULE_PARM_DESC(disable_hugepages,
56 		 "Disable VFIO IOMMU support for IOMMU hugepages.");
57 
58 static unsigned int dma_entry_limit __read_mostly = U16_MAX;
59 module_param_named(dma_entry_limit, dma_entry_limit, uint, 0644);
60 MODULE_PARM_DESC(dma_entry_limit,
61 		 "Maximum number of user DMA mappings per container (65535).");
62 
63 struct vfio_iommu {
64 	struct list_head	domain_list;
65 	struct list_head	iova_list;
66 	struct mutex		lock;
67 	struct rb_root		dma_list;
68 	struct list_head	device_list;
69 	struct mutex		device_list_lock;
70 	unsigned int		dma_avail;
71 	unsigned int		vaddr_invalid_count;
72 	uint64_t		pgsize_bitmap;
73 	uint64_t		num_non_pinned_groups;
74 	bool			v2;
75 	bool			nesting;
76 	bool			dirty_page_tracking;
77 	struct list_head	emulated_iommu_groups;
78 };
79 
80 struct vfio_domain {
81 	struct iommu_domain	*domain;
82 	struct list_head	next;
83 	struct list_head	group_list;
84 	bool			fgsp : 1;	/* Fine-grained super pages */
85 	bool			enforce_cache_coherency : 1;
86 };
87 
88 struct vfio_dma {
89 	struct rb_node		node;
90 	dma_addr_t		iova;		/* Device address */
91 	unsigned long		vaddr;		/* Process virtual addr */
92 	size_t			size;		/* Map size (bytes) */
93 	int			prot;		/* IOMMU_READ/WRITE */
94 	bool			iommu_mapped;
95 	bool			lock_cap;	/* capable(CAP_IPC_LOCK) */
96 	bool			vaddr_invalid;
97 	struct task_struct	*task;
98 	struct rb_root		pfn_list;	/* Ex-user pinned pfn list */
99 	unsigned long		*bitmap;
100 	struct mm_struct	*mm;
101 	size_t			locked_vm;
102 };
103 
104 struct vfio_batch {
105 	struct page		**pages;	/* for pin_user_pages_remote */
106 	struct page		*fallback_page; /* if pages alloc fails */
107 	int			capacity;	/* length of pages array */
108 	int			size;		/* of batch currently */
109 	int			offset;		/* of next entry in pages */
110 };
111 
112 struct vfio_iommu_group {
113 	struct iommu_group	*iommu_group;
114 	struct list_head	next;
115 	bool			pinned_page_dirty_scope;
116 };
117 
118 struct vfio_iova {
119 	struct list_head	list;
120 	dma_addr_t		start;
121 	dma_addr_t		end;
122 };
123 
124 /*
125  * Guest RAM pinning working set or DMA target
126  */
127 struct vfio_pfn {
128 	struct rb_node		node;
129 	dma_addr_t		iova;		/* Device address */
130 	unsigned long		pfn;		/* Host pfn */
131 	unsigned int		ref_count;
132 };
133 
134 struct vfio_regions {
135 	struct list_head list;
136 	dma_addr_t iova;
137 	phys_addr_t phys;
138 	size_t len;
139 };
140 
141 #define DIRTY_BITMAP_BYTES(n)	(ALIGN(n, BITS_PER_TYPE(u64)) / BITS_PER_BYTE)
142 
143 /*
144  * Input argument of number of bits to bitmap_set() is unsigned integer, which
145  * further casts to signed integer for unaligned multi-bit operation,
146  * __bitmap_set().
147  * Then maximum bitmap size supported is 2^31 bits divided by 2^3 bits/byte,
148  * that is 2^28 (256 MB) which maps to 2^31 * 2^12 = 2^43 (8TB) on 4K page
149  * system.
150  */
151 #define DIRTY_BITMAP_PAGES_MAX	 ((u64)INT_MAX)
152 #define DIRTY_BITMAP_SIZE_MAX	 DIRTY_BITMAP_BYTES(DIRTY_BITMAP_PAGES_MAX)
153 
154 static int put_pfn(unsigned long pfn, int prot);
155 
156 static struct vfio_iommu_group*
157 vfio_iommu_find_iommu_group(struct vfio_iommu *iommu,
158 			    struct iommu_group *iommu_group);
159 
160 /*
161  * This code handles mapping and unmapping of user data buffers
162  * into DMA'ble space using the IOMMU
163  */
164 
vfio_find_dma(struct vfio_iommu * iommu,dma_addr_t start,size_t size)165 static struct vfio_dma *vfio_find_dma(struct vfio_iommu *iommu,
166 				      dma_addr_t start, size_t size)
167 {
168 	struct rb_node *node = iommu->dma_list.rb_node;
169 
170 	while (node) {
171 		struct vfio_dma *dma = rb_entry(node, struct vfio_dma, node);
172 
173 		if (start + size <= dma->iova)
174 			node = node->rb_left;
175 		else if (start >= dma->iova + dma->size)
176 			node = node->rb_right;
177 		else
178 			return dma;
179 	}
180 
181 	return NULL;
182 }
183 
vfio_find_dma_first_node(struct vfio_iommu * iommu,dma_addr_t start,u64 size)184 static struct rb_node *vfio_find_dma_first_node(struct vfio_iommu *iommu,
185 						dma_addr_t start, u64 size)
186 {
187 	struct rb_node *res = NULL;
188 	struct rb_node *node = iommu->dma_list.rb_node;
189 	struct vfio_dma *dma_res = NULL;
190 
191 	while (node) {
192 		struct vfio_dma *dma = rb_entry(node, struct vfio_dma, node);
193 
194 		if (start < dma->iova + dma->size) {
195 			res = node;
196 			dma_res = dma;
197 			if (start >= dma->iova)
198 				break;
199 			node = node->rb_left;
200 		} else {
201 			node = node->rb_right;
202 		}
203 	}
204 	if (res && size && dma_res->iova >= start + size)
205 		res = NULL;
206 	return res;
207 }
208 
vfio_link_dma(struct vfio_iommu * iommu,struct vfio_dma * new)209 static void vfio_link_dma(struct vfio_iommu *iommu, struct vfio_dma *new)
210 {
211 	struct rb_node **link = &iommu->dma_list.rb_node, *parent = NULL;
212 	struct vfio_dma *dma;
213 
214 	while (*link) {
215 		parent = *link;
216 		dma = rb_entry(parent, struct vfio_dma, node);
217 
218 		if (new->iova + new->size <= dma->iova)
219 			link = &(*link)->rb_left;
220 		else
221 			link = &(*link)->rb_right;
222 	}
223 
224 	rb_link_node(&new->node, parent, link);
225 	rb_insert_color(&new->node, &iommu->dma_list);
226 }
227 
vfio_unlink_dma(struct vfio_iommu * iommu,struct vfio_dma * old)228 static void vfio_unlink_dma(struct vfio_iommu *iommu, struct vfio_dma *old)
229 {
230 	rb_erase(&old->node, &iommu->dma_list);
231 }
232 
233 
vfio_dma_bitmap_alloc(struct vfio_dma * dma,size_t pgsize)234 static int vfio_dma_bitmap_alloc(struct vfio_dma *dma, size_t pgsize)
235 {
236 	uint64_t npages = dma->size / pgsize;
237 
238 	if (npages > DIRTY_BITMAP_PAGES_MAX)
239 		return -EINVAL;
240 
241 	/*
242 	 * Allocate extra 64 bits that are used to calculate shift required for
243 	 * bitmap_shift_left() to manipulate and club unaligned number of pages
244 	 * in adjacent vfio_dma ranges.
245 	 */
246 	dma->bitmap = kvzalloc(DIRTY_BITMAP_BYTES(npages) + sizeof(u64),
247 			       GFP_KERNEL);
248 	if (!dma->bitmap)
249 		return -ENOMEM;
250 
251 	return 0;
252 }
253 
vfio_dma_bitmap_free(struct vfio_dma * dma)254 static void vfio_dma_bitmap_free(struct vfio_dma *dma)
255 {
256 	kvfree(dma->bitmap);
257 	dma->bitmap = NULL;
258 }
259 
vfio_dma_populate_bitmap(struct vfio_dma * dma,size_t pgsize)260 static void vfio_dma_populate_bitmap(struct vfio_dma *dma, size_t pgsize)
261 {
262 	struct rb_node *p;
263 	unsigned long pgshift = __ffs(pgsize);
264 
265 	for (p = rb_first(&dma->pfn_list); p; p = rb_next(p)) {
266 		struct vfio_pfn *vpfn = rb_entry(p, struct vfio_pfn, node);
267 
268 		bitmap_set(dma->bitmap, (vpfn->iova - dma->iova) >> pgshift, 1);
269 	}
270 }
271 
vfio_iommu_populate_bitmap_full(struct vfio_iommu * iommu)272 static void vfio_iommu_populate_bitmap_full(struct vfio_iommu *iommu)
273 {
274 	struct rb_node *n;
275 	unsigned long pgshift = __ffs(iommu->pgsize_bitmap);
276 
277 	for (n = rb_first(&iommu->dma_list); n; n = rb_next(n)) {
278 		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
279 
280 		bitmap_set(dma->bitmap, 0, dma->size >> pgshift);
281 	}
282 }
283 
vfio_dma_bitmap_alloc_all(struct vfio_iommu * iommu,size_t pgsize)284 static int vfio_dma_bitmap_alloc_all(struct vfio_iommu *iommu, size_t pgsize)
285 {
286 	struct rb_node *n;
287 
288 	for (n = rb_first(&iommu->dma_list); n; n = rb_next(n)) {
289 		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
290 		int ret;
291 
292 		ret = vfio_dma_bitmap_alloc(dma, pgsize);
293 		if (ret) {
294 			struct rb_node *p;
295 
296 			for (p = rb_prev(n); p; p = rb_prev(p)) {
297 				struct vfio_dma *dma = rb_entry(p,
298 							struct vfio_dma, node);
299 
300 				vfio_dma_bitmap_free(dma);
301 			}
302 			return ret;
303 		}
304 		vfio_dma_populate_bitmap(dma, pgsize);
305 	}
306 	return 0;
307 }
308 
vfio_dma_bitmap_free_all(struct vfio_iommu * iommu)309 static void vfio_dma_bitmap_free_all(struct vfio_iommu *iommu)
310 {
311 	struct rb_node *n;
312 
313 	for (n = rb_first(&iommu->dma_list); n; n = rb_next(n)) {
314 		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
315 
316 		vfio_dma_bitmap_free(dma);
317 	}
318 }
319 
320 /*
321  * Helper Functions for host iova-pfn list
322  */
vfio_find_vpfn(struct vfio_dma * dma,dma_addr_t iova)323 static struct vfio_pfn *vfio_find_vpfn(struct vfio_dma *dma, dma_addr_t iova)
324 {
325 	struct vfio_pfn *vpfn;
326 	struct rb_node *node = dma->pfn_list.rb_node;
327 
328 	while (node) {
329 		vpfn = rb_entry(node, struct vfio_pfn, node);
330 
331 		if (iova < vpfn->iova)
332 			node = node->rb_left;
333 		else if (iova > vpfn->iova)
334 			node = node->rb_right;
335 		else
336 			return vpfn;
337 	}
338 	return NULL;
339 }
340 
vfio_link_pfn(struct vfio_dma * dma,struct vfio_pfn * new)341 static void vfio_link_pfn(struct vfio_dma *dma,
342 			  struct vfio_pfn *new)
343 {
344 	struct rb_node **link, *parent = NULL;
345 	struct vfio_pfn *vpfn;
346 
347 	link = &dma->pfn_list.rb_node;
348 	while (*link) {
349 		parent = *link;
350 		vpfn = rb_entry(parent, struct vfio_pfn, node);
351 
352 		if (new->iova < vpfn->iova)
353 			link = &(*link)->rb_left;
354 		else
355 			link = &(*link)->rb_right;
356 	}
357 
358 	rb_link_node(&new->node, parent, link);
359 	rb_insert_color(&new->node, &dma->pfn_list);
360 }
361 
vfio_unlink_pfn(struct vfio_dma * dma,struct vfio_pfn * old)362 static void vfio_unlink_pfn(struct vfio_dma *dma, struct vfio_pfn *old)
363 {
364 	rb_erase(&old->node, &dma->pfn_list);
365 }
366 
vfio_add_to_pfn_list(struct vfio_dma * dma,dma_addr_t iova,unsigned long pfn)367 static int vfio_add_to_pfn_list(struct vfio_dma *dma, dma_addr_t iova,
368 				unsigned long pfn)
369 {
370 	struct vfio_pfn *vpfn;
371 
372 	vpfn = kzalloc(sizeof(*vpfn), GFP_KERNEL);
373 	if (!vpfn)
374 		return -ENOMEM;
375 
376 	vpfn->iova = iova;
377 	vpfn->pfn = pfn;
378 	vpfn->ref_count = 1;
379 	vfio_link_pfn(dma, vpfn);
380 	return 0;
381 }
382 
vfio_remove_from_pfn_list(struct vfio_dma * dma,struct vfio_pfn * vpfn)383 static void vfio_remove_from_pfn_list(struct vfio_dma *dma,
384 				      struct vfio_pfn *vpfn)
385 {
386 	vfio_unlink_pfn(dma, vpfn);
387 	kfree(vpfn);
388 }
389 
vfio_iova_get_vfio_pfn(struct vfio_dma * dma,unsigned long iova)390 static struct vfio_pfn *vfio_iova_get_vfio_pfn(struct vfio_dma *dma,
391 					       unsigned long iova)
392 {
393 	struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
394 
395 	if (vpfn)
396 		vpfn->ref_count++;
397 	return vpfn;
398 }
399 
vfio_iova_put_vfio_pfn(struct vfio_dma * dma,struct vfio_pfn * vpfn)400 static int vfio_iova_put_vfio_pfn(struct vfio_dma *dma, struct vfio_pfn *vpfn)
401 {
402 	int ret = 0;
403 
404 	vpfn->ref_count--;
405 	if (!vpfn->ref_count) {
406 		ret = put_pfn(vpfn->pfn, dma->prot);
407 		vfio_remove_from_pfn_list(dma, vpfn);
408 	}
409 	return ret;
410 }
411 
mm_lock_acct(struct task_struct * task,struct mm_struct * mm,bool lock_cap,long npage)412 static int mm_lock_acct(struct task_struct *task, struct mm_struct *mm,
413 			bool lock_cap, long npage)
414 {
415 	int ret = mmap_write_lock_killable(mm);
416 
417 	if (ret)
418 		return ret;
419 
420 	ret = __account_locked_vm(mm, abs(npage), npage > 0, task, lock_cap);
421 	mmap_write_unlock(mm);
422 	return ret;
423 }
424 
vfio_lock_acct(struct vfio_dma * dma,long npage,bool async)425 static int vfio_lock_acct(struct vfio_dma *dma, long npage, bool async)
426 {
427 	struct mm_struct *mm;
428 	int ret;
429 
430 	if (!npage)
431 		return 0;
432 
433 	mm = dma->mm;
434 	if (async && !mmget_not_zero(mm))
435 		return -ESRCH; /* process exited */
436 
437 	ret = mm_lock_acct(dma->task, mm, dma->lock_cap, npage);
438 	if (!ret)
439 		dma->locked_vm += npage;
440 
441 	if (async)
442 		mmput(mm);
443 
444 	return ret;
445 }
446 
447 /*
448  * Some mappings aren't backed by a struct page, for example an mmap'd
449  * MMIO range for our own or another device.  These use a different
450  * pfn conversion and shouldn't be tracked as locked pages.
451  * For compound pages, any driver that sets the reserved bit in head
452  * page needs to set the reserved bit in all subpages to be safe.
453  */
is_invalid_reserved_pfn(unsigned long pfn)454 static bool is_invalid_reserved_pfn(unsigned long pfn)
455 {
456 	if (pfn_valid(pfn))
457 		return PageReserved(pfn_to_page(pfn));
458 
459 	return true;
460 }
461 
put_pfn(unsigned long pfn,int prot)462 static int put_pfn(unsigned long pfn, int prot)
463 {
464 	if (!is_invalid_reserved_pfn(pfn)) {
465 		struct page *page = pfn_to_page(pfn);
466 
467 		unpin_user_pages_dirty_lock(&page, 1, prot & IOMMU_WRITE);
468 		return 1;
469 	}
470 	return 0;
471 }
472 
473 #define VFIO_BATCH_MAX_CAPACITY (PAGE_SIZE / sizeof(struct page *))
474 
vfio_batch_init(struct vfio_batch * batch)475 static void vfio_batch_init(struct vfio_batch *batch)
476 {
477 	batch->size = 0;
478 	batch->offset = 0;
479 
480 	if (unlikely(disable_hugepages))
481 		goto fallback;
482 
483 	batch->pages = (struct page **) __get_free_page(GFP_KERNEL);
484 	if (!batch->pages)
485 		goto fallback;
486 
487 	batch->capacity = VFIO_BATCH_MAX_CAPACITY;
488 	return;
489 
490 fallback:
491 	batch->pages = &batch->fallback_page;
492 	batch->capacity = 1;
493 }
494 
vfio_batch_unpin(struct vfio_batch * batch,struct vfio_dma * dma)495 static void vfio_batch_unpin(struct vfio_batch *batch, struct vfio_dma *dma)
496 {
497 	while (batch->size) {
498 		unsigned long pfn = page_to_pfn(batch->pages[batch->offset]);
499 
500 		put_pfn(pfn, dma->prot);
501 		batch->offset++;
502 		batch->size--;
503 	}
504 }
505 
vfio_batch_fini(struct vfio_batch * batch)506 static void vfio_batch_fini(struct vfio_batch *batch)
507 {
508 	if (batch->capacity == VFIO_BATCH_MAX_CAPACITY)
509 		free_page((unsigned long)batch->pages);
510 }
511 
follow_fault_pfn(struct vm_area_struct * vma,struct mm_struct * mm,unsigned long vaddr,unsigned long * pfn,bool write_fault)512 static int follow_fault_pfn(struct vm_area_struct *vma, struct mm_struct *mm,
513 			    unsigned long vaddr, unsigned long *pfn,
514 			    bool write_fault)
515 {
516 	struct follow_pfnmap_args args = { .vma = vma, .address = vaddr };
517 	int ret;
518 
519 	ret = follow_pfnmap_start(&args);
520 	if (ret) {
521 		bool unlocked = false;
522 
523 		ret = fixup_user_fault(mm, vaddr,
524 				       FAULT_FLAG_REMOTE |
525 				       (write_fault ?  FAULT_FLAG_WRITE : 0),
526 				       &unlocked);
527 		if (unlocked)
528 			return -EAGAIN;
529 
530 		if (ret)
531 			return ret;
532 
533 		ret = follow_pfnmap_start(&args);
534 		if (ret)
535 			return ret;
536 	}
537 
538 	if (write_fault && !args.writable)
539 		ret = -EFAULT;
540 	else
541 		*pfn = args.pfn;
542 
543 	follow_pfnmap_end(&args);
544 	return ret;
545 }
546 
547 /*
548  * Returns the positive number of pfns successfully obtained or a negative
549  * error code.
550  */
vaddr_get_pfns(struct mm_struct * mm,unsigned long vaddr,long npages,int prot,unsigned long * pfn,struct page ** pages)551 static int vaddr_get_pfns(struct mm_struct *mm, unsigned long vaddr,
552 			  long npages, int prot, unsigned long *pfn,
553 			  struct page **pages)
554 {
555 	struct vm_area_struct *vma;
556 	unsigned int flags = 0;
557 	int ret;
558 
559 	if (prot & IOMMU_WRITE)
560 		flags |= FOLL_WRITE;
561 
562 	mmap_read_lock(mm);
563 	ret = pin_user_pages_remote(mm, vaddr, npages, flags | FOLL_LONGTERM,
564 				    pages, NULL);
565 	if (ret > 0) {
566 		*pfn = page_to_pfn(pages[0]);
567 		goto done;
568 	}
569 
570 	vaddr = untagged_addr_remote(mm, vaddr);
571 
572 retry:
573 	vma = vma_lookup(mm, vaddr);
574 
575 	if (vma && vma->vm_flags & VM_PFNMAP) {
576 		ret = follow_fault_pfn(vma, mm, vaddr, pfn, prot & IOMMU_WRITE);
577 		if (ret == -EAGAIN)
578 			goto retry;
579 
580 		if (!ret) {
581 			if (is_invalid_reserved_pfn(*pfn))
582 				ret = 1;
583 			else
584 				ret = -EFAULT;
585 		}
586 	}
587 done:
588 	mmap_read_unlock(mm);
589 	return ret;
590 }
591 
592 /*
593  * Attempt to pin pages.  We really don't want to track all the pfns and
594  * the iommu can only map chunks of consecutive pfns anyway, so get the
595  * first page and all consecutive pages with the same locking.
596  */
vfio_pin_pages_remote(struct vfio_dma * dma,unsigned long vaddr,long npage,unsigned long * pfn_base,unsigned long limit,struct vfio_batch * batch)597 static long vfio_pin_pages_remote(struct vfio_dma *dma, unsigned long vaddr,
598 				  long npage, unsigned long *pfn_base,
599 				  unsigned long limit, struct vfio_batch *batch)
600 {
601 	unsigned long pfn;
602 	struct mm_struct *mm = current->mm;
603 	long ret, pinned = 0, lock_acct = 0;
604 	bool rsvd;
605 	dma_addr_t iova = vaddr - dma->vaddr + dma->iova;
606 
607 	/* This code path is only user initiated */
608 	if (!mm)
609 		return -ENODEV;
610 
611 	if (batch->size) {
612 		/* Leftover pages in batch from an earlier call. */
613 		*pfn_base = page_to_pfn(batch->pages[batch->offset]);
614 		pfn = *pfn_base;
615 		rsvd = is_invalid_reserved_pfn(*pfn_base);
616 	} else {
617 		*pfn_base = 0;
618 	}
619 
620 	while (npage) {
621 		if (!batch->size) {
622 			/*
623 			 * Large mappings may take a while to repeatedly refill
624 			 * the batch, so conditionally relinquish the CPU when
625 			 * needed to avoid stalls.
626 			 */
627 			cond_resched();
628 
629 			/* Empty batch, so refill it. */
630 			long req_pages = min_t(long, npage, batch->capacity);
631 
632 			ret = vaddr_get_pfns(mm, vaddr, req_pages, dma->prot,
633 					     &pfn, batch->pages);
634 			if (ret < 0)
635 				goto unpin_out;
636 
637 			batch->size = ret;
638 			batch->offset = 0;
639 
640 			if (!*pfn_base) {
641 				*pfn_base = pfn;
642 				rsvd = is_invalid_reserved_pfn(*pfn_base);
643 			}
644 		}
645 
646 		/*
647 		 * pfn is preset for the first iteration of this inner loop and
648 		 * updated at the end to handle a VM_PFNMAP pfn.  In that case,
649 		 * batch->pages isn't valid (there's no struct page), so allow
650 		 * batch->pages to be touched only when there's more than one
651 		 * pfn to check, which guarantees the pfns are from a
652 		 * !VM_PFNMAP vma.
653 		 */
654 		while (true) {
655 			if (pfn != *pfn_base + pinned ||
656 			    rsvd != is_invalid_reserved_pfn(pfn))
657 				goto out;
658 
659 			/*
660 			 * Reserved pages aren't counted against the user,
661 			 * externally pinned pages are already counted against
662 			 * the user.
663 			 */
664 			if (!rsvd && !vfio_find_vpfn(dma, iova)) {
665 				if (!dma->lock_cap &&
666 				    mm->locked_vm + lock_acct + 1 > limit) {
667 					pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n",
668 						__func__, limit << PAGE_SHIFT);
669 					ret = -ENOMEM;
670 					goto unpin_out;
671 				}
672 				lock_acct++;
673 			}
674 
675 			pinned++;
676 			npage--;
677 			vaddr += PAGE_SIZE;
678 			iova += PAGE_SIZE;
679 			batch->offset++;
680 			batch->size--;
681 
682 			if (!batch->size)
683 				break;
684 
685 			pfn = page_to_pfn(batch->pages[batch->offset]);
686 		}
687 
688 		if (unlikely(disable_hugepages))
689 			break;
690 	}
691 
692 out:
693 	ret = vfio_lock_acct(dma, lock_acct, false);
694 
695 unpin_out:
696 	if (batch->size == 1 && !batch->offset) {
697 		/* May be a VM_PFNMAP pfn, which the batch can't remember. */
698 		put_pfn(pfn, dma->prot);
699 		batch->size = 0;
700 	}
701 
702 	if (ret < 0) {
703 		if (pinned && !rsvd) {
704 			for (pfn = *pfn_base ; pinned ; pfn++, pinned--)
705 				put_pfn(pfn, dma->prot);
706 		}
707 		vfio_batch_unpin(batch, dma);
708 
709 		return ret;
710 	}
711 
712 	return pinned;
713 }
714 
vfio_unpin_pages_remote(struct vfio_dma * dma,dma_addr_t iova,unsigned long pfn,long npage,bool do_accounting)715 static long vfio_unpin_pages_remote(struct vfio_dma *dma, dma_addr_t iova,
716 				    unsigned long pfn, long npage,
717 				    bool do_accounting)
718 {
719 	long unlocked = 0, locked = 0;
720 	long i;
721 
722 	for (i = 0; i < npage; i++, iova += PAGE_SIZE) {
723 		if (put_pfn(pfn++, dma->prot)) {
724 			unlocked++;
725 			if (vfio_find_vpfn(dma, iova))
726 				locked++;
727 		}
728 	}
729 
730 	if (do_accounting)
731 		vfio_lock_acct(dma, locked - unlocked, true);
732 
733 	return unlocked;
734 }
735 
vfio_pin_page_external(struct vfio_dma * dma,unsigned long vaddr,unsigned long * pfn_base,bool do_accounting)736 static int vfio_pin_page_external(struct vfio_dma *dma, unsigned long vaddr,
737 				  unsigned long *pfn_base, bool do_accounting)
738 {
739 	struct page *pages[1];
740 	struct mm_struct *mm;
741 	int ret;
742 
743 	mm = dma->mm;
744 	if (!mmget_not_zero(mm))
745 		return -ENODEV;
746 
747 	ret = vaddr_get_pfns(mm, vaddr, 1, dma->prot, pfn_base, pages);
748 	if (ret != 1)
749 		goto out;
750 
751 	ret = 0;
752 
753 	if (do_accounting && !is_invalid_reserved_pfn(*pfn_base)) {
754 		ret = vfio_lock_acct(dma, 1, false);
755 		if (ret) {
756 			put_pfn(*pfn_base, dma->prot);
757 			if (ret == -ENOMEM)
758 				pr_warn("%s: Task %s (%d) RLIMIT_MEMLOCK "
759 					"(%ld) exceeded\n", __func__,
760 					dma->task->comm, task_pid_nr(dma->task),
761 					task_rlimit(dma->task, RLIMIT_MEMLOCK));
762 		}
763 	}
764 
765 out:
766 	mmput(mm);
767 	return ret;
768 }
769 
vfio_unpin_page_external(struct vfio_dma * dma,dma_addr_t iova,bool do_accounting)770 static int vfio_unpin_page_external(struct vfio_dma *dma, dma_addr_t iova,
771 				    bool do_accounting)
772 {
773 	int unlocked;
774 	struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
775 
776 	if (!vpfn)
777 		return 0;
778 
779 	unlocked = vfio_iova_put_vfio_pfn(dma, vpfn);
780 
781 	if (do_accounting)
782 		vfio_lock_acct(dma, -unlocked, true);
783 
784 	return unlocked;
785 }
786 
vfio_iommu_type1_pin_pages(void * iommu_data,struct iommu_group * iommu_group,dma_addr_t user_iova,int npage,int prot,struct page ** pages)787 static int vfio_iommu_type1_pin_pages(void *iommu_data,
788 				      struct iommu_group *iommu_group,
789 				      dma_addr_t user_iova,
790 				      int npage, int prot,
791 				      struct page **pages)
792 {
793 	struct vfio_iommu *iommu = iommu_data;
794 	struct vfio_iommu_group *group;
795 	int i, j, ret;
796 	unsigned long remote_vaddr;
797 	struct vfio_dma *dma;
798 	bool do_accounting;
799 
800 	if (!iommu || !pages)
801 		return -EINVAL;
802 
803 	/* Supported for v2 version only */
804 	if (!iommu->v2)
805 		return -EACCES;
806 
807 	mutex_lock(&iommu->lock);
808 
809 	if (WARN_ONCE(iommu->vaddr_invalid_count,
810 		      "vfio_pin_pages not allowed with VFIO_UPDATE_VADDR\n")) {
811 		ret = -EBUSY;
812 		goto pin_done;
813 	}
814 
815 	/* Fail if no dma_umap notifier is registered */
816 	if (list_empty(&iommu->device_list)) {
817 		ret = -EINVAL;
818 		goto pin_done;
819 	}
820 
821 	/*
822 	 * If iommu capable domain exist in the container then all pages are
823 	 * already pinned and accounted. Accounting should be done if there is no
824 	 * iommu capable domain in the container.
825 	 */
826 	do_accounting = list_empty(&iommu->domain_list);
827 
828 	for (i = 0; i < npage; i++) {
829 		unsigned long phys_pfn;
830 		dma_addr_t iova;
831 		struct vfio_pfn *vpfn;
832 
833 		iova = user_iova + PAGE_SIZE * i;
834 		dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
835 		if (!dma) {
836 			ret = -EINVAL;
837 			goto pin_unwind;
838 		}
839 
840 		if ((dma->prot & prot) != prot) {
841 			ret = -EPERM;
842 			goto pin_unwind;
843 		}
844 
845 		vpfn = vfio_iova_get_vfio_pfn(dma, iova);
846 		if (vpfn) {
847 			pages[i] = pfn_to_page(vpfn->pfn);
848 			continue;
849 		}
850 
851 		remote_vaddr = dma->vaddr + (iova - dma->iova);
852 		ret = vfio_pin_page_external(dma, remote_vaddr, &phys_pfn,
853 					     do_accounting);
854 		if (ret)
855 			goto pin_unwind;
856 
857 		if (!pfn_valid(phys_pfn)) {
858 			ret = -EINVAL;
859 			goto pin_unwind;
860 		}
861 
862 		ret = vfio_add_to_pfn_list(dma, iova, phys_pfn);
863 		if (ret) {
864 			if (put_pfn(phys_pfn, dma->prot) && do_accounting)
865 				vfio_lock_acct(dma, -1, true);
866 			goto pin_unwind;
867 		}
868 
869 		pages[i] = pfn_to_page(phys_pfn);
870 
871 		if (iommu->dirty_page_tracking) {
872 			unsigned long pgshift = __ffs(iommu->pgsize_bitmap);
873 
874 			/*
875 			 * Bitmap populated with the smallest supported page
876 			 * size
877 			 */
878 			bitmap_set(dma->bitmap,
879 				   (iova - dma->iova) >> pgshift, 1);
880 		}
881 	}
882 	ret = i;
883 
884 	group = vfio_iommu_find_iommu_group(iommu, iommu_group);
885 	if (!group->pinned_page_dirty_scope) {
886 		group->pinned_page_dirty_scope = true;
887 		iommu->num_non_pinned_groups--;
888 	}
889 
890 	goto pin_done;
891 
892 pin_unwind:
893 	pages[i] = NULL;
894 	for (j = 0; j < i; j++) {
895 		dma_addr_t iova;
896 
897 		iova = user_iova + PAGE_SIZE * j;
898 		dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
899 		vfio_unpin_page_external(dma, iova, do_accounting);
900 		pages[j] = NULL;
901 	}
902 pin_done:
903 	mutex_unlock(&iommu->lock);
904 	return ret;
905 }
906 
vfio_iommu_type1_unpin_pages(void * iommu_data,dma_addr_t user_iova,int npage)907 static void vfio_iommu_type1_unpin_pages(void *iommu_data,
908 					 dma_addr_t user_iova, int npage)
909 {
910 	struct vfio_iommu *iommu = iommu_data;
911 	bool do_accounting;
912 	int i;
913 
914 	/* Supported for v2 version only */
915 	if (WARN_ON(!iommu->v2))
916 		return;
917 
918 	mutex_lock(&iommu->lock);
919 
920 	do_accounting = list_empty(&iommu->domain_list);
921 	for (i = 0; i < npage; i++) {
922 		dma_addr_t iova = user_iova + PAGE_SIZE * i;
923 		struct vfio_dma *dma;
924 
925 		dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
926 		if (!dma)
927 			break;
928 
929 		vfio_unpin_page_external(dma, iova, do_accounting);
930 	}
931 
932 	mutex_unlock(&iommu->lock);
933 
934 	WARN_ON(i != npage);
935 }
936 
vfio_sync_unpin(struct vfio_dma * dma,struct vfio_domain * domain,struct list_head * regions,struct iommu_iotlb_gather * iotlb_gather)937 static long vfio_sync_unpin(struct vfio_dma *dma, struct vfio_domain *domain,
938 			    struct list_head *regions,
939 			    struct iommu_iotlb_gather *iotlb_gather)
940 {
941 	long unlocked = 0;
942 	struct vfio_regions *entry, *next;
943 
944 	iommu_iotlb_sync(domain->domain, iotlb_gather);
945 
946 	list_for_each_entry_safe(entry, next, regions, list) {
947 		unlocked += vfio_unpin_pages_remote(dma,
948 						    entry->iova,
949 						    entry->phys >> PAGE_SHIFT,
950 						    entry->len >> PAGE_SHIFT,
951 						    false);
952 		list_del(&entry->list);
953 		kfree(entry);
954 	}
955 
956 	cond_resched();
957 
958 	return unlocked;
959 }
960 
961 /*
962  * Generally, VFIO needs to unpin remote pages after each IOTLB flush.
963  * Therefore, when using IOTLB flush sync interface, VFIO need to keep track
964  * of these regions (currently using a list).
965  *
966  * This value specifies maximum number of regions for each IOTLB flush sync.
967  */
968 #define VFIO_IOMMU_TLB_SYNC_MAX		512
969 
unmap_unpin_fast(struct vfio_domain * domain,struct vfio_dma * dma,dma_addr_t * iova,size_t len,phys_addr_t phys,long * unlocked,struct list_head * unmapped_list,int * unmapped_cnt,struct iommu_iotlb_gather * iotlb_gather)970 static size_t unmap_unpin_fast(struct vfio_domain *domain,
971 			       struct vfio_dma *dma, dma_addr_t *iova,
972 			       size_t len, phys_addr_t phys, long *unlocked,
973 			       struct list_head *unmapped_list,
974 			       int *unmapped_cnt,
975 			       struct iommu_iotlb_gather *iotlb_gather)
976 {
977 	size_t unmapped = 0;
978 	struct vfio_regions *entry = kzalloc(sizeof(*entry), GFP_KERNEL);
979 
980 	if (entry) {
981 		unmapped = iommu_unmap_fast(domain->domain, *iova, len,
982 					    iotlb_gather);
983 
984 		if (!unmapped) {
985 			kfree(entry);
986 		} else {
987 			entry->iova = *iova;
988 			entry->phys = phys;
989 			entry->len  = unmapped;
990 			list_add_tail(&entry->list, unmapped_list);
991 
992 			*iova += unmapped;
993 			(*unmapped_cnt)++;
994 		}
995 	}
996 
997 	/*
998 	 * Sync if the number of fast-unmap regions hits the limit
999 	 * or in case of errors.
1000 	 */
1001 	if (*unmapped_cnt >= VFIO_IOMMU_TLB_SYNC_MAX || !unmapped) {
1002 		*unlocked += vfio_sync_unpin(dma, domain, unmapped_list,
1003 					     iotlb_gather);
1004 		*unmapped_cnt = 0;
1005 	}
1006 
1007 	return unmapped;
1008 }
1009 
unmap_unpin_slow(struct vfio_domain * domain,struct vfio_dma * dma,dma_addr_t * iova,size_t len,phys_addr_t phys,long * unlocked)1010 static size_t unmap_unpin_slow(struct vfio_domain *domain,
1011 			       struct vfio_dma *dma, dma_addr_t *iova,
1012 			       size_t len, phys_addr_t phys,
1013 			       long *unlocked)
1014 {
1015 	size_t unmapped = iommu_unmap(domain->domain, *iova, len);
1016 
1017 	if (unmapped) {
1018 		*unlocked += vfio_unpin_pages_remote(dma, *iova,
1019 						     phys >> PAGE_SHIFT,
1020 						     unmapped >> PAGE_SHIFT,
1021 						     false);
1022 		*iova += unmapped;
1023 		cond_resched();
1024 	}
1025 	return unmapped;
1026 }
1027 
vfio_unmap_unpin(struct vfio_iommu * iommu,struct vfio_dma * dma,bool do_accounting)1028 static long vfio_unmap_unpin(struct vfio_iommu *iommu, struct vfio_dma *dma,
1029 			     bool do_accounting)
1030 {
1031 	dma_addr_t iova = dma->iova, end = dma->iova + dma->size;
1032 	struct vfio_domain *domain, *d;
1033 	LIST_HEAD(unmapped_region_list);
1034 	struct iommu_iotlb_gather iotlb_gather;
1035 	int unmapped_region_cnt = 0;
1036 	long unlocked = 0;
1037 
1038 	if (!dma->size)
1039 		return 0;
1040 
1041 	if (list_empty(&iommu->domain_list))
1042 		return 0;
1043 
1044 	/*
1045 	 * We use the IOMMU to track the physical addresses, otherwise we'd
1046 	 * need a much more complicated tracking system.  Unfortunately that
1047 	 * means we need to use one of the iommu domains to figure out the
1048 	 * pfns to unpin.  The rest need to be unmapped in advance so we have
1049 	 * no iommu translations remaining when the pages are unpinned.
1050 	 */
1051 	domain = d = list_first_entry(&iommu->domain_list,
1052 				      struct vfio_domain, next);
1053 
1054 	list_for_each_entry_continue(d, &iommu->domain_list, next) {
1055 		iommu_unmap(d->domain, dma->iova, dma->size);
1056 		cond_resched();
1057 	}
1058 
1059 	iommu_iotlb_gather_init(&iotlb_gather);
1060 	while (iova < end) {
1061 		size_t unmapped, len;
1062 		phys_addr_t phys, next;
1063 
1064 		phys = iommu_iova_to_phys(domain->domain, iova);
1065 		if (WARN_ON(!phys)) {
1066 			iova += PAGE_SIZE;
1067 			continue;
1068 		}
1069 
1070 		/*
1071 		 * To optimize for fewer iommu_unmap() calls, each of which
1072 		 * may require hardware cache flushing, try to find the
1073 		 * largest contiguous physical memory chunk to unmap.
1074 		 */
1075 		for (len = PAGE_SIZE;
1076 		     !domain->fgsp && iova + len < end; len += PAGE_SIZE) {
1077 			next = iommu_iova_to_phys(domain->domain, iova + len);
1078 			if (next != phys + len)
1079 				break;
1080 		}
1081 
1082 		/*
1083 		 * First, try to use fast unmap/unpin. In case of failure,
1084 		 * switch to slow unmap/unpin path.
1085 		 */
1086 		unmapped = unmap_unpin_fast(domain, dma, &iova, len, phys,
1087 					    &unlocked, &unmapped_region_list,
1088 					    &unmapped_region_cnt,
1089 					    &iotlb_gather);
1090 		if (!unmapped) {
1091 			unmapped = unmap_unpin_slow(domain, dma, &iova, len,
1092 						    phys, &unlocked);
1093 			if (WARN_ON(!unmapped))
1094 				break;
1095 		}
1096 	}
1097 
1098 	dma->iommu_mapped = false;
1099 
1100 	if (unmapped_region_cnt) {
1101 		unlocked += vfio_sync_unpin(dma, domain, &unmapped_region_list,
1102 					    &iotlb_gather);
1103 	}
1104 
1105 	if (do_accounting) {
1106 		vfio_lock_acct(dma, -unlocked, true);
1107 		return 0;
1108 	}
1109 	return unlocked;
1110 }
1111 
vfio_remove_dma(struct vfio_iommu * iommu,struct vfio_dma * dma)1112 static void vfio_remove_dma(struct vfio_iommu *iommu, struct vfio_dma *dma)
1113 {
1114 	WARN_ON(!RB_EMPTY_ROOT(&dma->pfn_list));
1115 	vfio_unmap_unpin(iommu, dma, true);
1116 	vfio_unlink_dma(iommu, dma);
1117 	put_task_struct(dma->task);
1118 	mmdrop(dma->mm);
1119 	vfio_dma_bitmap_free(dma);
1120 	if (dma->vaddr_invalid)
1121 		iommu->vaddr_invalid_count--;
1122 	kfree(dma);
1123 	iommu->dma_avail++;
1124 }
1125 
vfio_update_pgsize_bitmap(struct vfio_iommu * iommu)1126 static void vfio_update_pgsize_bitmap(struct vfio_iommu *iommu)
1127 {
1128 	struct vfio_domain *domain;
1129 
1130 	iommu->pgsize_bitmap = ULONG_MAX;
1131 
1132 	list_for_each_entry(domain, &iommu->domain_list, next)
1133 		iommu->pgsize_bitmap &= domain->domain->pgsize_bitmap;
1134 
1135 	/*
1136 	 * In case the IOMMU supports page sizes smaller than PAGE_SIZE
1137 	 * we pretend PAGE_SIZE is supported and hide sub-PAGE_SIZE sizes.
1138 	 * That way the user will be able to map/unmap buffers whose size/
1139 	 * start address is aligned with PAGE_SIZE. Pinning code uses that
1140 	 * granularity while iommu driver can use the sub-PAGE_SIZE size
1141 	 * to map the buffer.
1142 	 */
1143 	if (iommu->pgsize_bitmap & ~PAGE_MASK) {
1144 		iommu->pgsize_bitmap &= PAGE_MASK;
1145 		iommu->pgsize_bitmap |= PAGE_SIZE;
1146 	}
1147 }
1148 
update_user_bitmap(u64 __user * bitmap,struct vfio_iommu * iommu,struct vfio_dma * dma,dma_addr_t base_iova,size_t pgsize)1149 static int update_user_bitmap(u64 __user *bitmap, struct vfio_iommu *iommu,
1150 			      struct vfio_dma *dma, dma_addr_t base_iova,
1151 			      size_t pgsize)
1152 {
1153 	unsigned long pgshift = __ffs(pgsize);
1154 	unsigned long nbits = dma->size >> pgshift;
1155 	unsigned long bit_offset = (dma->iova - base_iova) >> pgshift;
1156 	unsigned long copy_offset = bit_offset / BITS_PER_LONG;
1157 	unsigned long shift = bit_offset % BITS_PER_LONG;
1158 	unsigned long leftover;
1159 
1160 	/*
1161 	 * mark all pages dirty if any IOMMU capable device is not able
1162 	 * to report dirty pages and all pages are pinned and mapped.
1163 	 */
1164 	if (iommu->num_non_pinned_groups && dma->iommu_mapped)
1165 		bitmap_set(dma->bitmap, 0, nbits);
1166 
1167 	if (shift) {
1168 		bitmap_shift_left(dma->bitmap, dma->bitmap, shift,
1169 				  nbits + shift);
1170 
1171 		if (copy_from_user(&leftover,
1172 				   (void __user *)(bitmap + copy_offset),
1173 				   sizeof(leftover)))
1174 			return -EFAULT;
1175 
1176 		bitmap_or(dma->bitmap, dma->bitmap, &leftover, shift);
1177 	}
1178 
1179 	if (copy_to_user((void __user *)(bitmap + copy_offset), dma->bitmap,
1180 			 DIRTY_BITMAP_BYTES(nbits + shift)))
1181 		return -EFAULT;
1182 
1183 	return 0;
1184 }
1185 
vfio_iova_dirty_bitmap(u64 __user * bitmap,struct vfio_iommu * iommu,dma_addr_t iova,size_t size,size_t pgsize)1186 static int vfio_iova_dirty_bitmap(u64 __user *bitmap, struct vfio_iommu *iommu,
1187 				  dma_addr_t iova, size_t size, size_t pgsize)
1188 {
1189 	struct vfio_dma *dma;
1190 	struct rb_node *n;
1191 	unsigned long pgshift = __ffs(pgsize);
1192 	int ret;
1193 
1194 	/*
1195 	 * GET_BITMAP request must fully cover vfio_dma mappings.  Multiple
1196 	 * vfio_dma mappings may be clubbed by specifying large ranges, but
1197 	 * there must not be any previous mappings bisected by the range.
1198 	 * An error will be returned if these conditions are not met.
1199 	 */
1200 	dma = vfio_find_dma(iommu, iova, 1);
1201 	if (dma && dma->iova != iova)
1202 		return -EINVAL;
1203 
1204 	dma = vfio_find_dma(iommu, iova + size - 1, 0);
1205 	if (dma && dma->iova + dma->size != iova + size)
1206 		return -EINVAL;
1207 
1208 	for (n = rb_first(&iommu->dma_list); n; n = rb_next(n)) {
1209 		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
1210 
1211 		if (dma->iova < iova)
1212 			continue;
1213 
1214 		if (dma->iova > iova + size - 1)
1215 			break;
1216 
1217 		ret = update_user_bitmap(bitmap, iommu, dma, iova, pgsize);
1218 		if (ret)
1219 			return ret;
1220 
1221 		/*
1222 		 * Re-populate bitmap to include all pinned pages which are
1223 		 * considered as dirty but exclude pages which are unpinned and
1224 		 * pages which are marked dirty by vfio_dma_rw()
1225 		 */
1226 		bitmap_clear(dma->bitmap, 0, dma->size >> pgshift);
1227 		vfio_dma_populate_bitmap(dma, pgsize);
1228 	}
1229 	return 0;
1230 }
1231 
verify_bitmap_size(uint64_t npages,uint64_t bitmap_size)1232 static int verify_bitmap_size(uint64_t npages, uint64_t bitmap_size)
1233 {
1234 	if (!npages || !bitmap_size || (bitmap_size > DIRTY_BITMAP_SIZE_MAX) ||
1235 	    (bitmap_size < DIRTY_BITMAP_BYTES(npages)))
1236 		return -EINVAL;
1237 
1238 	return 0;
1239 }
1240 
1241 /*
1242  * Notify VFIO drivers using vfio_register_emulated_iommu_dev() to invalidate
1243  * and unmap iovas within the range we're about to unmap. Drivers MUST unpin
1244  * pages in response to an invalidation.
1245  */
vfio_notify_dma_unmap(struct vfio_iommu * iommu,struct vfio_dma * dma)1246 static void vfio_notify_dma_unmap(struct vfio_iommu *iommu,
1247 				  struct vfio_dma *dma)
1248 {
1249 	struct vfio_device *device;
1250 
1251 	if (list_empty(&iommu->device_list))
1252 		return;
1253 
1254 	/*
1255 	 * The device is expected to call vfio_unpin_pages() for any IOVA it has
1256 	 * pinned within the range. Since vfio_unpin_pages() will eventually
1257 	 * call back down to this code and try to obtain the iommu->lock we must
1258 	 * drop it.
1259 	 */
1260 	mutex_lock(&iommu->device_list_lock);
1261 	mutex_unlock(&iommu->lock);
1262 
1263 	list_for_each_entry(device, &iommu->device_list, iommu_entry)
1264 		device->ops->dma_unmap(device, dma->iova, dma->size);
1265 
1266 	mutex_unlock(&iommu->device_list_lock);
1267 	mutex_lock(&iommu->lock);
1268 }
1269 
vfio_dma_do_unmap(struct vfio_iommu * iommu,struct vfio_iommu_type1_dma_unmap * unmap,struct vfio_bitmap * bitmap)1270 static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
1271 			     struct vfio_iommu_type1_dma_unmap *unmap,
1272 			     struct vfio_bitmap *bitmap)
1273 {
1274 	struct vfio_dma *dma, *dma_last = NULL;
1275 	size_t unmapped = 0, pgsize;
1276 	int ret = -EINVAL, retries = 0;
1277 	unsigned long pgshift;
1278 	dma_addr_t iova = unmap->iova;
1279 	u64 size = unmap->size;
1280 	bool unmap_all = unmap->flags & VFIO_DMA_UNMAP_FLAG_ALL;
1281 	bool invalidate_vaddr = unmap->flags & VFIO_DMA_UNMAP_FLAG_VADDR;
1282 	struct rb_node *n, *first_n;
1283 
1284 	mutex_lock(&iommu->lock);
1285 
1286 	/* Cannot update vaddr if mdev is present. */
1287 	if (invalidate_vaddr && !list_empty(&iommu->emulated_iommu_groups)) {
1288 		ret = -EBUSY;
1289 		goto unlock;
1290 	}
1291 
1292 	pgshift = __ffs(iommu->pgsize_bitmap);
1293 	pgsize = (size_t)1 << pgshift;
1294 
1295 	if (iova & (pgsize - 1))
1296 		goto unlock;
1297 
1298 	if (unmap_all) {
1299 		if (iova || size)
1300 			goto unlock;
1301 		size = U64_MAX;
1302 	} else if (!size || size & (pgsize - 1) ||
1303 		   iova + size - 1 < iova || size > SIZE_MAX) {
1304 		goto unlock;
1305 	}
1306 
1307 	/* When dirty tracking is enabled, allow only min supported pgsize */
1308 	if ((unmap->flags & VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP) &&
1309 	    (!iommu->dirty_page_tracking || (bitmap->pgsize != pgsize))) {
1310 		goto unlock;
1311 	}
1312 
1313 	WARN_ON((pgsize - 1) & PAGE_MASK);
1314 again:
1315 	/*
1316 	 * vfio-iommu-type1 (v1) - User mappings were coalesced together to
1317 	 * avoid tracking individual mappings.  This means that the granularity
1318 	 * of the original mapping was lost and the user was allowed to attempt
1319 	 * to unmap any range.  Depending on the contiguousness of physical
1320 	 * memory and page sizes supported by the IOMMU, arbitrary unmaps may
1321 	 * or may not have worked.  We only guaranteed unmap granularity
1322 	 * matching the original mapping; even though it was untracked here,
1323 	 * the original mappings are reflected in IOMMU mappings.  This
1324 	 * resulted in a couple unusual behaviors.  First, if a range is not
1325 	 * able to be unmapped, ex. a set of 4k pages that was mapped as a
1326 	 * 2M hugepage into the IOMMU, the unmap ioctl returns success but with
1327 	 * a zero sized unmap.  Also, if an unmap request overlaps the first
1328 	 * address of a hugepage, the IOMMU will unmap the entire hugepage.
1329 	 * This also returns success and the returned unmap size reflects the
1330 	 * actual size unmapped.
1331 	 *
1332 	 * We attempt to maintain compatibility with this "v1" interface, but
1333 	 * we take control out of the hands of the IOMMU.  Therefore, an unmap
1334 	 * request offset from the beginning of the original mapping will
1335 	 * return success with zero sized unmap.  And an unmap request covering
1336 	 * the first iova of mapping will unmap the entire range.
1337 	 *
1338 	 * The v2 version of this interface intends to be more deterministic.
1339 	 * Unmap requests must fully cover previous mappings.  Multiple
1340 	 * mappings may still be unmaped by specifying large ranges, but there
1341 	 * must not be any previous mappings bisected by the range.  An error
1342 	 * will be returned if these conditions are not met.  The v2 interface
1343 	 * will only return success and a size of zero if there were no
1344 	 * mappings within the range.
1345 	 */
1346 	if (iommu->v2 && !unmap_all) {
1347 		dma = vfio_find_dma(iommu, iova, 1);
1348 		if (dma && dma->iova != iova)
1349 			goto unlock;
1350 
1351 		dma = vfio_find_dma(iommu, iova + size - 1, 0);
1352 		if (dma && dma->iova + dma->size != iova + size)
1353 			goto unlock;
1354 	}
1355 
1356 	ret = 0;
1357 	n = first_n = vfio_find_dma_first_node(iommu, iova, size);
1358 
1359 	while (n) {
1360 		dma = rb_entry(n, struct vfio_dma, node);
1361 		if (dma->iova >= iova + size)
1362 			break;
1363 
1364 		if (!iommu->v2 && iova > dma->iova)
1365 			break;
1366 
1367 		if (invalidate_vaddr) {
1368 			if (dma->vaddr_invalid) {
1369 				struct rb_node *last_n = n;
1370 
1371 				for (n = first_n; n != last_n; n = rb_next(n)) {
1372 					dma = rb_entry(n,
1373 						       struct vfio_dma, node);
1374 					dma->vaddr_invalid = false;
1375 					iommu->vaddr_invalid_count--;
1376 				}
1377 				ret = -EINVAL;
1378 				unmapped = 0;
1379 				break;
1380 			}
1381 			dma->vaddr_invalid = true;
1382 			iommu->vaddr_invalid_count++;
1383 			unmapped += dma->size;
1384 			n = rb_next(n);
1385 			continue;
1386 		}
1387 
1388 		if (!RB_EMPTY_ROOT(&dma->pfn_list)) {
1389 			if (dma_last == dma) {
1390 				BUG_ON(++retries > 10);
1391 			} else {
1392 				dma_last = dma;
1393 				retries = 0;
1394 			}
1395 
1396 			vfio_notify_dma_unmap(iommu, dma);
1397 			goto again;
1398 		}
1399 
1400 		if (unmap->flags & VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP) {
1401 			ret = update_user_bitmap(bitmap->data, iommu, dma,
1402 						 iova, pgsize);
1403 			if (ret)
1404 				break;
1405 		}
1406 
1407 		unmapped += dma->size;
1408 		n = rb_next(n);
1409 		vfio_remove_dma(iommu, dma);
1410 	}
1411 
1412 unlock:
1413 	mutex_unlock(&iommu->lock);
1414 
1415 	/* Report how much was unmapped */
1416 	unmap->size = unmapped;
1417 
1418 	return ret;
1419 }
1420 
vfio_iommu_map(struct vfio_iommu * iommu,dma_addr_t iova,unsigned long pfn,long npage,int prot)1421 static int vfio_iommu_map(struct vfio_iommu *iommu, dma_addr_t iova,
1422 			  unsigned long pfn, long npage, int prot)
1423 {
1424 	struct vfio_domain *d;
1425 	int ret;
1426 
1427 	list_for_each_entry(d, &iommu->domain_list, next) {
1428 		ret = iommu_map(d->domain, iova, (phys_addr_t)pfn << PAGE_SHIFT,
1429 				npage << PAGE_SHIFT, prot | IOMMU_CACHE,
1430 				GFP_KERNEL_ACCOUNT);
1431 		if (ret)
1432 			goto unwind;
1433 
1434 		cond_resched();
1435 	}
1436 
1437 	return 0;
1438 
1439 unwind:
1440 	list_for_each_entry_continue_reverse(d, &iommu->domain_list, next) {
1441 		iommu_unmap(d->domain, iova, npage << PAGE_SHIFT);
1442 		cond_resched();
1443 	}
1444 
1445 	return ret;
1446 }
1447 
vfio_pin_map_dma(struct vfio_iommu * iommu,struct vfio_dma * dma,size_t map_size)1448 static int vfio_pin_map_dma(struct vfio_iommu *iommu, struct vfio_dma *dma,
1449 			    size_t map_size)
1450 {
1451 	dma_addr_t iova = dma->iova;
1452 	unsigned long vaddr = dma->vaddr;
1453 	struct vfio_batch batch;
1454 	size_t size = map_size;
1455 	long npage;
1456 	unsigned long pfn, limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1457 	int ret = 0;
1458 
1459 	vfio_batch_init(&batch);
1460 
1461 	while (size) {
1462 		/* Pin a contiguous chunk of memory */
1463 		npage = vfio_pin_pages_remote(dma, vaddr + dma->size,
1464 					      size >> PAGE_SHIFT, &pfn, limit,
1465 					      &batch);
1466 		if (npage <= 0) {
1467 			WARN_ON(!npage);
1468 			ret = (int)npage;
1469 			break;
1470 		}
1471 
1472 		/* Map it! */
1473 		ret = vfio_iommu_map(iommu, iova + dma->size, pfn, npage,
1474 				     dma->prot);
1475 		if (ret) {
1476 			vfio_unpin_pages_remote(dma, iova + dma->size, pfn,
1477 						npage, true);
1478 			vfio_batch_unpin(&batch, dma);
1479 			break;
1480 		}
1481 
1482 		size -= npage << PAGE_SHIFT;
1483 		dma->size += npage << PAGE_SHIFT;
1484 	}
1485 
1486 	vfio_batch_fini(&batch);
1487 	dma->iommu_mapped = true;
1488 
1489 	if (ret)
1490 		vfio_remove_dma(iommu, dma);
1491 
1492 	return ret;
1493 }
1494 
1495 /*
1496  * Check dma map request is within a valid iova range
1497  */
vfio_iommu_iova_dma_valid(struct vfio_iommu * iommu,dma_addr_t start,dma_addr_t end)1498 static bool vfio_iommu_iova_dma_valid(struct vfio_iommu *iommu,
1499 				      dma_addr_t start, dma_addr_t end)
1500 {
1501 	struct list_head *iova = &iommu->iova_list;
1502 	struct vfio_iova *node;
1503 
1504 	list_for_each_entry(node, iova, list) {
1505 		if (start >= node->start && end <= node->end)
1506 			return true;
1507 	}
1508 
1509 	/*
1510 	 * Check for list_empty() as well since a container with
1511 	 * a single mdev device will have an empty list.
1512 	 */
1513 	return list_empty(iova);
1514 }
1515 
vfio_change_dma_owner(struct vfio_dma * dma)1516 static int vfio_change_dma_owner(struct vfio_dma *dma)
1517 {
1518 	struct task_struct *task = current->group_leader;
1519 	struct mm_struct *mm = current->mm;
1520 	long npage = dma->locked_vm;
1521 	bool lock_cap;
1522 	int ret;
1523 
1524 	if (mm == dma->mm)
1525 		return 0;
1526 
1527 	lock_cap = capable(CAP_IPC_LOCK);
1528 	ret = mm_lock_acct(task, mm, lock_cap, npage);
1529 	if (ret)
1530 		return ret;
1531 
1532 	if (mmget_not_zero(dma->mm)) {
1533 		mm_lock_acct(dma->task, dma->mm, dma->lock_cap, -npage);
1534 		mmput(dma->mm);
1535 	}
1536 
1537 	if (dma->task != task) {
1538 		put_task_struct(dma->task);
1539 		dma->task = get_task_struct(task);
1540 	}
1541 	mmdrop(dma->mm);
1542 	dma->mm = mm;
1543 	mmgrab(dma->mm);
1544 	dma->lock_cap = lock_cap;
1545 	return 0;
1546 }
1547 
vfio_dma_do_map(struct vfio_iommu * iommu,struct vfio_iommu_type1_dma_map * map)1548 static int vfio_dma_do_map(struct vfio_iommu *iommu,
1549 			   struct vfio_iommu_type1_dma_map *map)
1550 {
1551 	bool set_vaddr = map->flags & VFIO_DMA_MAP_FLAG_VADDR;
1552 	dma_addr_t iova = map->iova;
1553 	unsigned long vaddr = map->vaddr;
1554 	size_t size = map->size;
1555 	int ret = 0, prot = 0;
1556 	size_t pgsize;
1557 	struct vfio_dma *dma;
1558 
1559 	/* Verify that none of our __u64 fields overflow */
1560 	if (map->size != size || map->vaddr != vaddr || map->iova != iova)
1561 		return -EINVAL;
1562 
1563 	/* READ/WRITE from device perspective */
1564 	if (map->flags & VFIO_DMA_MAP_FLAG_WRITE)
1565 		prot |= IOMMU_WRITE;
1566 	if (map->flags & VFIO_DMA_MAP_FLAG_READ)
1567 		prot |= IOMMU_READ;
1568 
1569 	if ((prot && set_vaddr) || (!prot && !set_vaddr))
1570 		return -EINVAL;
1571 
1572 	mutex_lock(&iommu->lock);
1573 
1574 	pgsize = (size_t)1 << __ffs(iommu->pgsize_bitmap);
1575 
1576 	WARN_ON((pgsize - 1) & PAGE_MASK);
1577 
1578 	if (!size || (size | iova | vaddr) & (pgsize - 1)) {
1579 		ret = -EINVAL;
1580 		goto out_unlock;
1581 	}
1582 
1583 	/* Don't allow IOVA or virtual address wrap */
1584 	if (iova + size - 1 < iova || vaddr + size - 1 < vaddr) {
1585 		ret = -EINVAL;
1586 		goto out_unlock;
1587 	}
1588 
1589 	dma = vfio_find_dma(iommu, iova, size);
1590 	if (set_vaddr) {
1591 		if (!dma) {
1592 			ret = -ENOENT;
1593 		} else if (!dma->vaddr_invalid || dma->iova != iova ||
1594 			   dma->size != size) {
1595 			ret = -EINVAL;
1596 		} else {
1597 			ret = vfio_change_dma_owner(dma);
1598 			if (ret)
1599 				goto out_unlock;
1600 			dma->vaddr = vaddr;
1601 			dma->vaddr_invalid = false;
1602 			iommu->vaddr_invalid_count--;
1603 		}
1604 		goto out_unlock;
1605 	} else if (dma) {
1606 		ret = -EEXIST;
1607 		goto out_unlock;
1608 	}
1609 
1610 	if (!iommu->dma_avail) {
1611 		ret = -ENOSPC;
1612 		goto out_unlock;
1613 	}
1614 
1615 	if (!vfio_iommu_iova_dma_valid(iommu, iova, iova + size - 1)) {
1616 		ret = -EINVAL;
1617 		goto out_unlock;
1618 	}
1619 
1620 	dma = kzalloc(sizeof(*dma), GFP_KERNEL);
1621 	if (!dma) {
1622 		ret = -ENOMEM;
1623 		goto out_unlock;
1624 	}
1625 
1626 	iommu->dma_avail--;
1627 	dma->iova = iova;
1628 	dma->vaddr = vaddr;
1629 	dma->prot = prot;
1630 
1631 	/*
1632 	 * We need to be able to both add to a task's locked memory and test
1633 	 * against the locked memory limit and we need to be able to do both
1634 	 * outside of this call path as pinning can be asynchronous via the
1635 	 * external interfaces for mdev devices.  RLIMIT_MEMLOCK requires a
1636 	 * task_struct. Save the group_leader so that all DMA tracking uses
1637 	 * the same task, to make debugging easier.  VM locked pages requires
1638 	 * an mm_struct, so grab the mm in case the task dies.
1639 	 */
1640 	get_task_struct(current->group_leader);
1641 	dma->task = current->group_leader;
1642 	dma->lock_cap = capable(CAP_IPC_LOCK);
1643 	dma->mm = current->mm;
1644 	mmgrab(dma->mm);
1645 
1646 	dma->pfn_list = RB_ROOT;
1647 
1648 	/* Insert zero-sized and grow as we map chunks of it */
1649 	vfio_link_dma(iommu, dma);
1650 
1651 	/* Don't pin and map if container doesn't contain IOMMU capable domain*/
1652 	if (list_empty(&iommu->domain_list))
1653 		dma->size = size;
1654 	else
1655 		ret = vfio_pin_map_dma(iommu, dma, size);
1656 
1657 	if (!ret && iommu->dirty_page_tracking) {
1658 		ret = vfio_dma_bitmap_alloc(dma, pgsize);
1659 		if (ret)
1660 			vfio_remove_dma(iommu, dma);
1661 	}
1662 
1663 out_unlock:
1664 	mutex_unlock(&iommu->lock);
1665 	return ret;
1666 }
1667 
vfio_iommu_replay(struct vfio_iommu * iommu,struct vfio_domain * domain)1668 static int vfio_iommu_replay(struct vfio_iommu *iommu,
1669 			     struct vfio_domain *domain)
1670 {
1671 	struct vfio_batch batch;
1672 	struct vfio_domain *d = NULL;
1673 	struct rb_node *n;
1674 	unsigned long limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1675 	int ret;
1676 
1677 	/* Arbitrarily pick the first domain in the list for lookups */
1678 	if (!list_empty(&iommu->domain_list))
1679 		d = list_first_entry(&iommu->domain_list,
1680 				     struct vfio_domain, next);
1681 
1682 	vfio_batch_init(&batch);
1683 
1684 	n = rb_first(&iommu->dma_list);
1685 
1686 	for (; n; n = rb_next(n)) {
1687 		struct vfio_dma *dma;
1688 		dma_addr_t iova;
1689 
1690 		dma = rb_entry(n, struct vfio_dma, node);
1691 		iova = dma->iova;
1692 
1693 		while (iova < dma->iova + dma->size) {
1694 			phys_addr_t phys;
1695 			size_t size;
1696 
1697 			if (dma->iommu_mapped) {
1698 				phys_addr_t p;
1699 				dma_addr_t i;
1700 
1701 				if (WARN_ON(!d)) { /* mapped w/o a domain?! */
1702 					ret = -EINVAL;
1703 					goto unwind;
1704 				}
1705 
1706 				phys = iommu_iova_to_phys(d->domain, iova);
1707 
1708 				if (WARN_ON(!phys)) {
1709 					iova += PAGE_SIZE;
1710 					continue;
1711 				}
1712 
1713 				size = PAGE_SIZE;
1714 				p = phys + size;
1715 				i = iova + size;
1716 				while (i < dma->iova + dma->size &&
1717 				       p == iommu_iova_to_phys(d->domain, i)) {
1718 					size += PAGE_SIZE;
1719 					p += PAGE_SIZE;
1720 					i += PAGE_SIZE;
1721 				}
1722 			} else {
1723 				unsigned long pfn;
1724 				unsigned long vaddr = dma->vaddr +
1725 						     (iova - dma->iova);
1726 				size_t n = dma->iova + dma->size - iova;
1727 				long npage;
1728 
1729 				npage = vfio_pin_pages_remote(dma, vaddr,
1730 							      n >> PAGE_SHIFT,
1731 							      &pfn, limit,
1732 							      &batch);
1733 				if (npage <= 0) {
1734 					WARN_ON(!npage);
1735 					ret = (int)npage;
1736 					goto unwind;
1737 				}
1738 
1739 				phys = pfn << PAGE_SHIFT;
1740 				size = npage << PAGE_SHIFT;
1741 			}
1742 
1743 			ret = iommu_map(domain->domain, iova, phys, size,
1744 					dma->prot | IOMMU_CACHE,
1745 					GFP_KERNEL_ACCOUNT);
1746 			if (ret) {
1747 				if (!dma->iommu_mapped) {
1748 					vfio_unpin_pages_remote(dma, iova,
1749 							phys >> PAGE_SHIFT,
1750 							size >> PAGE_SHIFT,
1751 							true);
1752 					vfio_batch_unpin(&batch, dma);
1753 				}
1754 				goto unwind;
1755 			}
1756 
1757 			iova += size;
1758 		}
1759 	}
1760 
1761 	/* All dmas are now mapped, defer to second tree walk for unwind */
1762 	for (n = rb_first(&iommu->dma_list); n; n = rb_next(n)) {
1763 		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
1764 
1765 		dma->iommu_mapped = true;
1766 	}
1767 
1768 	vfio_batch_fini(&batch);
1769 	return 0;
1770 
1771 unwind:
1772 	for (; n; n = rb_prev(n)) {
1773 		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
1774 		dma_addr_t iova;
1775 
1776 		if (dma->iommu_mapped) {
1777 			iommu_unmap(domain->domain, dma->iova, dma->size);
1778 			continue;
1779 		}
1780 
1781 		iova = dma->iova;
1782 		while (iova < dma->iova + dma->size) {
1783 			phys_addr_t phys, p;
1784 			size_t size;
1785 			dma_addr_t i;
1786 
1787 			phys = iommu_iova_to_phys(domain->domain, iova);
1788 			if (!phys) {
1789 				iova += PAGE_SIZE;
1790 				continue;
1791 			}
1792 
1793 			size = PAGE_SIZE;
1794 			p = phys + size;
1795 			i = iova + size;
1796 			while (i < dma->iova + dma->size &&
1797 			       p == iommu_iova_to_phys(domain->domain, i)) {
1798 				size += PAGE_SIZE;
1799 				p += PAGE_SIZE;
1800 				i += PAGE_SIZE;
1801 			}
1802 
1803 			iommu_unmap(domain->domain, iova, size);
1804 			vfio_unpin_pages_remote(dma, iova, phys >> PAGE_SHIFT,
1805 						size >> PAGE_SHIFT, true);
1806 		}
1807 	}
1808 
1809 	vfio_batch_fini(&batch);
1810 	return ret;
1811 }
1812 
1813 /*
1814  * We change our unmap behavior slightly depending on whether the IOMMU
1815  * supports fine-grained superpages.  IOMMUs like AMD-Vi will use a superpage
1816  * for practically any contiguous power-of-two mapping we give it.  This means
1817  * we don't need to look for contiguous chunks ourselves to make unmapping
1818  * more efficient.  On IOMMUs with coarse-grained super pages, like Intel VT-d
1819  * with discrete 2M/1G/512G/1T superpages, identifying contiguous chunks
1820  * significantly boosts non-hugetlbfs mappings and doesn't seem to hurt when
1821  * hugetlbfs is in use.
1822  */
vfio_test_domain_fgsp(struct vfio_domain * domain,struct list_head * regions)1823 static void vfio_test_domain_fgsp(struct vfio_domain *domain, struct list_head *regions)
1824 {
1825 	int ret, order = get_order(PAGE_SIZE * 2);
1826 	struct vfio_iova *region;
1827 	struct page *pages;
1828 	dma_addr_t start;
1829 
1830 	pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, order);
1831 	if (!pages)
1832 		return;
1833 
1834 	list_for_each_entry(region, regions, list) {
1835 		start = ALIGN(region->start, PAGE_SIZE * 2);
1836 		if (start >= region->end || (region->end - start < PAGE_SIZE * 2))
1837 			continue;
1838 
1839 		ret = iommu_map(domain->domain, start, page_to_phys(pages), PAGE_SIZE * 2,
1840 				IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE,
1841 				GFP_KERNEL_ACCOUNT);
1842 		if (!ret) {
1843 			size_t unmapped = iommu_unmap(domain->domain, start, PAGE_SIZE);
1844 
1845 			if (unmapped == PAGE_SIZE)
1846 				iommu_unmap(domain->domain, start + PAGE_SIZE, PAGE_SIZE);
1847 			else
1848 				domain->fgsp = true;
1849 		}
1850 		break;
1851 	}
1852 
1853 	__free_pages(pages, order);
1854 }
1855 
find_iommu_group(struct vfio_domain * domain,struct iommu_group * iommu_group)1856 static struct vfio_iommu_group *find_iommu_group(struct vfio_domain *domain,
1857 						 struct iommu_group *iommu_group)
1858 {
1859 	struct vfio_iommu_group *g;
1860 
1861 	list_for_each_entry(g, &domain->group_list, next) {
1862 		if (g->iommu_group == iommu_group)
1863 			return g;
1864 	}
1865 
1866 	return NULL;
1867 }
1868 
1869 static struct vfio_iommu_group*
vfio_iommu_find_iommu_group(struct vfio_iommu * iommu,struct iommu_group * iommu_group)1870 vfio_iommu_find_iommu_group(struct vfio_iommu *iommu,
1871 			    struct iommu_group *iommu_group)
1872 {
1873 	struct vfio_iommu_group *group;
1874 	struct vfio_domain *domain;
1875 
1876 	list_for_each_entry(domain, &iommu->domain_list, next) {
1877 		group = find_iommu_group(domain, iommu_group);
1878 		if (group)
1879 			return group;
1880 	}
1881 
1882 	list_for_each_entry(group, &iommu->emulated_iommu_groups, next)
1883 		if (group->iommu_group == iommu_group)
1884 			return group;
1885 	return NULL;
1886 }
1887 
vfio_iommu_has_sw_msi(struct list_head * group_resv_regions,phys_addr_t * base)1888 static bool vfio_iommu_has_sw_msi(struct list_head *group_resv_regions,
1889 				  phys_addr_t *base)
1890 {
1891 	struct iommu_resv_region *region;
1892 	bool ret = false;
1893 
1894 	list_for_each_entry(region, group_resv_regions, list) {
1895 		/*
1896 		 * The presence of any 'real' MSI regions should take
1897 		 * precedence over the software-managed one if the
1898 		 * IOMMU driver happens to advertise both types.
1899 		 */
1900 		if (region->type == IOMMU_RESV_MSI) {
1901 			ret = false;
1902 			break;
1903 		}
1904 
1905 		if (region->type == IOMMU_RESV_SW_MSI) {
1906 			*base = region->start;
1907 			ret = true;
1908 		}
1909 	}
1910 
1911 	return ret;
1912 }
1913 
1914 /*
1915  * This is a helper function to insert an address range to iova list.
1916  * The list is initially created with a single entry corresponding to
1917  * the IOMMU domain geometry to which the device group is attached.
1918  * The list aperture gets modified when a new domain is added to the
1919  * container if the new aperture doesn't conflict with the current one
1920  * or with any existing dma mappings. The list is also modified to
1921  * exclude any reserved regions associated with the device group.
1922  */
vfio_iommu_iova_insert(struct list_head * head,dma_addr_t start,dma_addr_t end)1923 static int vfio_iommu_iova_insert(struct list_head *head,
1924 				  dma_addr_t start, dma_addr_t end)
1925 {
1926 	struct vfio_iova *region;
1927 
1928 	region = kmalloc(sizeof(*region), GFP_KERNEL);
1929 	if (!region)
1930 		return -ENOMEM;
1931 
1932 	INIT_LIST_HEAD(&region->list);
1933 	region->start = start;
1934 	region->end = end;
1935 
1936 	list_add_tail(&region->list, head);
1937 	return 0;
1938 }
1939 
1940 /*
1941  * Check the new iommu aperture conflicts with existing aper or with any
1942  * existing dma mappings.
1943  */
vfio_iommu_aper_conflict(struct vfio_iommu * iommu,dma_addr_t start,dma_addr_t end)1944 static bool vfio_iommu_aper_conflict(struct vfio_iommu *iommu,
1945 				     dma_addr_t start, dma_addr_t end)
1946 {
1947 	struct vfio_iova *first, *last;
1948 	struct list_head *iova = &iommu->iova_list;
1949 
1950 	if (list_empty(iova))
1951 		return false;
1952 
1953 	/* Disjoint sets, return conflict */
1954 	first = list_first_entry(iova, struct vfio_iova, list);
1955 	last = list_last_entry(iova, struct vfio_iova, list);
1956 	if (start > last->end || end < first->start)
1957 		return true;
1958 
1959 	/* Check for any existing dma mappings below the new start */
1960 	if (start > first->start) {
1961 		if (vfio_find_dma(iommu, first->start, start - first->start))
1962 			return true;
1963 	}
1964 
1965 	/* Check for any existing dma mappings beyond the new end */
1966 	if (end < last->end) {
1967 		if (vfio_find_dma(iommu, end + 1, last->end - end))
1968 			return true;
1969 	}
1970 
1971 	return false;
1972 }
1973 
1974 /*
1975  * Resize iommu iova aperture window. This is called only if the new
1976  * aperture has no conflict with existing aperture and dma mappings.
1977  */
vfio_iommu_aper_resize(struct list_head * iova,dma_addr_t start,dma_addr_t end)1978 static int vfio_iommu_aper_resize(struct list_head *iova,
1979 				  dma_addr_t start, dma_addr_t end)
1980 {
1981 	struct vfio_iova *node, *next;
1982 
1983 	if (list_empty(iova))
1984 		return vfio_iommu_iova_insert(iova, start, end);
1985 
1986 	/* Adjust iova list start */
1987 	list_for_each_entry_safe(node, next, iova, list) {
1988 		if (start < node->start)
1989 			break;
1990 		if (start >= node->start && start < node->end) {
1991 			node->start = start;
1992 			break;
1993 		}
1994 		/* Delete nodes before new start */
1995 		list_del(&node->list);
1996 		kfree(node);
1997 	}
1998 
1999 	/* Adjust iova list end */
2000 	list_for_each_entry_safe(node, next, iova, list) {
2001 		if (end > node->end)
2002 			continue;
2003 		if (end > node->start && end <= node->end) {
2004 			node->end = end;
2005 			continue;
2006 		}
2007 		/* Delete nodes after new end */
2008 		list_del(&node->list);
2009 		kfree(node);
2010 	}
2011 
2012 	return 0;
2013 }
2014 
2015 /*
2016  * Check reserved region conflicts with existing dma mappings
2017  */
vfio_iommu_resv_conflict(struct vfio_iommu * iommu,struct list_head * resv_regions)2018 static bool vfio_iommu_resv_conflict(struct vfio_iommu *iommu,
2019 				     struct list_head *resv_regions)
2020 {
2021 	struct iommu_resv_region *region;
2022 
2023 	/* Check for conflict with existing dma mappings */
2024 	list_for_each_entry(region, resv_regions, list) {
2025 		if (region->type == IOMMU_RESV_DIRECT_RELAXABLE)
2026 			continue;
2027 
2028 		if (vfio_find_dma(iommu, region->start, region->length))
2029 			return true;
2030 	}
2031 
2032 	return false;
2033 }
2034 
2035 /*
2036  * Check iova region overlap with  reserved regions and
2037  * exclude them from the iommu iova range
2038  */
vfio_iommu_resv_exclude(struct list_head * iova,struct list_head * resv_regions)2039 static int vfio_iommu_resv_exclude(struct list_head *iova,
2040 				   struct list_head *resv_regions)
2041 {
2042 	struct iommu_resv_region *resv;
2043 	struct vfio_iova *n, *next;
2044 
2045 	list_for_each_entry(resv, resv_regions, list) {
2046 		phys_addr_t start, end;
2047 
2048 		if (resv->type == IOMMU_RESV_DIRECT_RELAXABLE)
2049 			continue;
2050 
2051 		start = resv->start;
2052 		end = resv->start + resv->length - 1;
2053 
2054 		list_for_each_entry_safe(n, next, iova, list) {
2055 			int ret = 0;
2056 
2057 			/* No overlap */
2058 			if (start > n->end || end < n->start)
2059 				continue;
2060 			/*
2061 			 * Insert a new node if current node overlaps with the
2062 			 * reserve region to exclude that from valid iova range.
2063 			 * Note that, new node is inserted before the current
2064 			 * node and finally the current node is deleted keeping
2065 			 * the list updated and sorted.
2066 			 */
2067 			if (start > n->start)
2068 				ret = vfio_iommu_iova_insert(&n->list, n->start,
2069 							     start - 1);
2070 			if (!ret && end < n->end)
2071 				ret = vfio_iommu_iova_insert(&n->list, end + 1,
2072 							     n->end);
2073 			if (ret)
2074 				return ret;
2075 
2076 			list_del(&n->list);
2077 			kfree(n);
2078 		}
2079 	}
2080 
2081 	if (list_empty(iova))
2082 		return -EINVAL;
2083 
2084 	return 0;
2085 }
2086 
vfio_iommu_resv_free(struct list_head * resv_regions)2087 static void vfio_iommu_resv_free(struct list_head *resv_regions)
2088 {
2089 	struct iommu_resv_region *n, *next;
2090 
2091 	list_for_each_entry_safe(n, next, resv_regions, list) {
2092 		list_del(&n->list);
2093 		kfree(n);
2094 	}
2095 }
2096 
vfio_iommu_iova_free(struct list_head * iova)2097 static void vfio_iommu_iova_free(struct list_head *iova)
2098 {
2099 	struct vfio_iova *n, *next;
2100 
2101 	list_for_each_entry_safe(n, next, iova, list) {
2102 		list_del(&n->list);
2103 		kfree(n);
2104 	}
2105 }
2106 
vfio_iommu_iova_get_copy(struct vfio_iommu * iommu,struct list_head * iova_copy)2107 static int vfio_iommu_iova_get_copy(struct vfio_iommu *iommu,
2108 				    struct list_head *iova_copy)
2109 {
2110 	struct list_head *iova = &iommu->iova_list;
2111 	struct vfio_iova *n;
2112 	int ret;
2113 
2114 	list_for_each_entry(n, iova, list) {
2115 		ret = vfio_iommu_iova_insert(iova_copy, n->start, n->end);
2116 		if (ret)
2117 			goto out_free;
2118 	}
2119 
2120 	return 0;
2121 
2122 out_free:
2123 	vfio_iommu_iova_free(iova_copy);
2124 	return ret;
2125 }
2126 
vfio_iommu_iova_insert_copy(struct vfio_iommu * iommu,struct list_head * iova_copy)2127 static void vfio_iommu_iova_insert_copy(struct vfio_iommu *iommu,
2128 					struct list_head *iova_copy)
2129 {
2130 	struct list_head *iova = &iommu->iova_list;
2131 
2132 	vfio_iommu_iova_free(iova);
2133 
2134 	list_splice_tail(iova_copy, iova);
2135 }
2136 
vfio_iommu_domain_alloc(struct device * dev,void * data)2137 static int vfio_iommu_domain_alloc(struct device *dev, void *data)
2138 {
2139 	struct iommu_domain **domain = data;
2140 
2141 	*domain = iommu_paging_domain_alloc(dev);
2142 	return 1; /* Don't iterate */
2143 }
2144 
vfio_iommu_type1_attach_group(void * iommu_data,struct iommu_group * iommu_group,enum vfio_group_type type)2145 static int vfio_iommu_type1_attach_group(void *iommu_data,
2146 		struct iommu_group *iommu_group, enum vfio_group_type type)
2147 {
2148 	struct vfio_iommu *iommu = iommu_data;
2149 	struct vfio_iommu_group *group;
2150 	struct vfio_domain *domain, *d;
2151 	bool resv_msi;
2152 	phys_addr_t resv_msi_base = 0;
2153 	struct iommu_domain_geometry *geo;
2154 	LIST_HEAD(iova_copy);
2155 	LIST_HEAD(group_resv_regions);
2156 	int ret = -EBUSY;
2157 
2158 	mutex_lock(&iommu->lock);
2159 
2160 	/* Attach could require pinning, so disallow while vaddr is invalid. */
2161 	if (iommu->vaddr_invalid_count)
2162 		goto out_unlock;
2163 
2164 	/* Check for duplicates */
2165 	ret = -EINVAL;
2166 	if (vfio_iommu_find_iommu_group(iommu, iommu_group))
2167 		goto out_unlock;
2168 
2169 	ret = -ENOMEM;
2170 	group = kzalloc(sizeof(*group), GFP_KERNEL);
2171 	if (!group)
2172 		goto out_unlock;
2173 	group->iommu_group = iommu_group;
2174 
2175 	if (type == VFIO_EMULATED_IOMMU) {
2176 		list_add(&group->next, &iommu->emulated_iommu_groups);
2177 		/*
2178 		 * An emulated IOMMU group cannot dirty memory directly, it can
2179 		 * only use interfaces that provide dirty tracking.
2180 		 * The iommu scope can only be promoted with the addition of a
2181 		 * dirty tracking group.
2182 		 */
2183 		group->pinned_page_dirty_scope = true;
2184 		ret = 0;
2185 		goto out_unlock;
2186 	}
2187 
2188 	ret = -ENOMEM;
2189 	domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2190 	if (!domain)
2191 		goto out_free_group;
2192 
2193 	/*
2194 	 * Going via the iommu_group iterator avoids races, and trivially gives
2195 	 * us a representative device for the IOMMU API call. We don't actually
2196 	 * want to iterate beyond the first device (if any).
2197 	 */
2198 	iommu_group_for_each_dev(iommu_group, &domain->domain,
2199 				 vfio_iommu_domain_alloc);
2200 	if (IS_ERR(domain->domain)) {
2201 		ret = PTR_ERR(domain->domain);
2202 		goto out_free_domain;
2203 	}
2204 
2205 	if (iommu->nesting) {
2206 		ret = iommu_enable_nesting(domain->domain);
2207 		if (ret)
2208 			goto out_domain;
2209 	}
2210 
2211 	ret = iommu_attach_group(domain->domain, group->iommu_group);
2212 	if (ret)
2213 		goto out_domain;
2214 
2215 	/* Get aperture info */
2216 	geo = &domain->domain->geometry;
2217 	if (vfio_iommu_aper_conflict(iommu, geo->aperture_start,
2218 				     geo->aperture_end)) {
2219 		ret = -EINVAL;
2220 		goto out_detach;
2221 	}
2222 
2223 	ret = iommu_get_group_resv_regions(iommu_group, &group_resv_regions);
2224 	if (ret)
2225 		goto out_detach;
2226 
2227 	if (vfio_iommu_resv_conflict(iommu, &group_resv_regions)) {
2228 		ret = -EINVAL;
2229 		goto out_detach;
2230 	}
2231 
2232 	/*
2233 	 * We don't want to work on the original iova list as the list
2234 	 * gets modified and in case of failure we have to retain the
2235 	 * original list. Get a copy here.
2236 	 */
2237 	ret = vfio_iommu_iova_get_copy(iommu, &iova_copy);
2238 	if (ret)
2239 		goto out_detach;
2240 
2241 	ret = vfio_iommu_aper_resize(&iova_copy, geo->aperture_start,
2242 				     geo->aperture_end);
2243 	if (ret)
2244 		goto out_detach;
2245 
2246 	ret = vfio_iommu_resv_exclude(&iova_copy, &group_resv_regions);
2247 	if (ret)
2248 		goto out_detach;
2249 
2250 	resv_msi = vfio_iommu_has_sw_msi(&group_resv_regions, &resv_msi_base);
2251 
2252 	INIT_LIST_HEAD(&domain->group_list);
2253 	list_add(&group->next, &domain->group_list);
2254 
2255 	if (!allow_unsafe_interrupts &&
2256 	    !iommu_group_has_isolated_msi(iommu_group)) {
2257 		pr_warn("%s: No interrupt remapping support.  Use the module param \"allow_unsafe_interrupts\" to enable VFIO IOMMU support on this platform\n",
2258 		       __func__);
2259 		ret = -EPERM;
2260 		goto out_detach;
2261 	}
2262 
2263 	/*
2264 	 * If the IOMMU can block non-coherent operations (ie PCIe TLPs with
2265 	 * no-snoop set) then VFIO always turns this feature on because on Intel
2266 	 * platforms it optimizes KVM to disable wbinvd emulation.
2267 	 */
2268 	if (domain->domain->ops->enforce_cache_coherency)
2269 		domain->enforce_cache_coherency =
2270 			domain->domain->ops->enforce_cache_coherency(
2271 				domain->domain);
2272 
2273 	/*
2274 	 * Try to match an existing compatible domain.  We don't want to
2275 	 * preclude an IOMMU driver supporting multiple bus_types and being
2276 	 * able to include different bus_types in the same IOMMU domain, so
2277 	 * we test whether the domains use the same iommu_ops rather than
2278 	 * testing if they're on the same bus_type.
2279 	 */
2280 	list_for_each_entry(d, &iommu->domain_list, next) {
2281 		if (d->domain->ops == domain->domain->ops &&
2282 		    d->enforce_cache_coherency ==
2283 			    domain->enforce_cache_coherency) {
2284 			iommu_detach_group(domain->domain, group->iommu_group);
2285 			if (!iommu_attach_group(d->domain,
2286 						group->iommu_group)) {
2287 				list_add(&group->next, &d->group_list);
2288 				iommu_domain_free(domain->domain);
2289 				kfree(domain);
2290 				goto done;
2291 			}
2292 
2293 			ret = iommu_attach_group(domain->domain,
2294 						 group->iommu_group);
2295 			if (ret)
2296 				goto out_domain;
2297 		}
2298 	}
2299 
2300 	vfio_test_domain_fgsp(domain, &iova_copy);
2301 
2302 	/* replay mappings on new domains */
2303 	ret = vfio_iommu_replay(iommu, domain);
2304 	if (ret)
2305 		goto out_detach;
2306 
2307 	if (resv_msi) {
2308 		ret = iommu_get_msi_cookie(domain->domain, resv_msi_base);
2309 		if (ret && ret != -ENODEV)
2310 			goto out_detach;
2311 	}
2312 
2313 	list_add(&domain->next, &iommu->domain_list);
2314 	vfio_update_pgsize_bitmap(iommu);
2315 done:
2316 	/* Delete the old one and insert new iova list */
2317 	vfio_iommu_iova_insert_copy(iommu, &iova_copy);
2318 
2319 	/*
2320 	 * An iommu backed group can dirty memory directly and therefore
2321 	 * demotes the iommu scope until it declares itself dirty tracking
2322 	 * capable via the page pinning interface.
2323 	 */
2324 	iommu->num_non_pinned_groups++;
2325 	mutex_unlock(&iommu->lock);
2326 	vfio_iommu_resv_free(&group_resv_regions);
2327 
2328 	return 0;
2329 
2330 out_detach:
2331 	iommu_detach_group(domain->domain, group->iommu_group);
2332 out_domain:
2333 	iommu_domain_free(domain->domain);
2334 	vfio_iommu_iova_free(&iova_copy);
2335 	vfio_iommu_resv_free(&group_resv_regions);
2336 out_free_domain:
2337 	kfree(domain);
2338 out_free_group:
2339 	kfree(group);
2340 out_unlock:
2341 	mutex_unlock(&iommu->lock);
2342 	return ret;
2343 }
2344 
vfio_iommu_unmap_unpin_all(struct vfio_iommu * iommu)2345 static void vfio_iommu_unmap_unpin_all(struct vfio_iommu *iommu)
2346 {
2347 	struct rb_node *node;
2348 
2349 	while ((node = rb_first(&iommu->dma_list)))
2350 		vfio_remove_dma(iommu, rb_entry(node, struct vfio_dma, node));
2351 }
2352 
vfio_iommu_unmap_unpin_reaccount(struct vfio_iommu * iommu)2353 static void vfio_iommu_unmap_unpin_reaccount(struct vfio_iommu *iommu)
2354 {
2355 	struct rb_node *n, *p;
2356 
2357 	n = rb_first(&iommu->dma_list);
2358 	for (; n; n = rb_next(n)) {
2359 		struct vfio_dma *dma;
2360 		long locked = 0, unlocked = 0;
2361 
2362 		dma = rb_entry(n, struct vfio_dma, node);
2363 		unlocked += vfio_unmap_unpin(iommu, dma, false);
2364 		p = rb_first(&dma->pfn_list);
2365 		for (; p; p = rb_next(p)) {
2366 			struct vfio_pfn *vpfn = rb_entry(p, struct vfio_pfn,
2367 							 node);
2368 
2369 			if (!is_invalid_reserved_pfn(vpfn->pfn))
2370 				locked++;
2371 		}
2372 		vfio_lock_acct(dma, locked - unlocked, true);
2373 	}
2374 }
2375 
2376 /*
2377  * Called when a domain is removed in detach. It is possible that
2378  * the removed domain decided the iova aperture window. Modify the
2379  * iova aperture with the smallest window among existing domains.
2380  */
vfio_iommu_aper_expand(struct vfio_iommu * iommu,struct list_head * iova_copy)2381 static void vfio_iommu_aper_expand(struct vfio_iommu *iommu,
2382 				   struct list_head *iova_copy)
2383 {
2384 	struct vfio_domain *domain;
2385 	struct vfio_iova *node;
2386 	dma_addr_t start = 0;
2387 	dma_addr_t end = (dma_addr_t)~0;
2388 
2389 	if (list_empty(iova_copy))
2390 		return;
2391 
2392 	list_for_each_entry(domain, &iommu->domain_list, next) {
2393 		struct iommu_domain_geometry *geo = &domain->domain->geometry;
2394 
2395 		if (geo->aperture_start > start)
2396 			start = geo->aperture_start;
2397 		if (geo->aperture_end < end)
2398 			end = geo->aperture_end;
2399 	}
2400 
2401 	/* Modify aperture limits. The new aper is either same or bigger */
2402 	node = list_first_entry(iova_copy, struct vfio_iova, list);
2403 	node->start = start;
2404 	node = list_last_entry(iova_copy, struct vfio_iova, list);
2405 	node->end = end;
2406 }
2407 
2408 /*
2409  * Called when a group is detached. The reserved regions for that
2410  * group can be part of valid iova now. But since reserved regions
2411  * may be duplicated among groups, populate the iova valid regions
2412  * list again.
2413  */
vfio_iommu_resv_refresh(struct vfio_iommu * iommu,struct list_head * iova_copy)2414 static int vfio_iommu_resv_refresh(struct vfio_iommu *iommu,
2415 				   struct list_head *iova_copy)
2416 {
2417 	struct vfio_domain *d;
2418 	struct vfio_iommu_group *g;
2419 	struct vfio_iova *node;
2420 	dma_addr_t start, end;
2421 	LIST_HEAD(resv_regions);
2422 	int ret;
2423 
2424 	if (list_empty(iova_copy))
2425 		return -EINVAL;
2426 
2427 	list_for_each_entry(d, &iommu->domain_list, next) {
2428 		list_for_each_entry(g, &d->group_list, next) {
2429 			ret = iommu_get_group_resv_regions(g->iommu_group,
2430 							   &resv_regions);
2431 			if (ret)
2432 				goto done;
2433 		}
2434 	}
2435 
2436 	node = list_first_entry(iova_copy, struct vfio_iova, list);
2437 	start = node->start;
2438 	node = list_last_entry(iova_copy, struct vfio_iova, list);
2439 	end = node->end;
2440 
2441 	/* purge the iova list and create new one */
2442 	vfio_iommu_iova_free(iova_copy);
2443 
2444 	ret = vfio_iommu_aper_resize(iova_copy, start, end);
2445 	if (ret)
2446 		goto done;
2447 
2448 	/* Exclude current reserved regions from iova ranges */
2449 	ret = vfio_iommu_resv_exclude(iova_copy, &resv_regions);
2450 done:
2451 	vfio_iommu_resv_free(&resv_regions);
2452 	return ret;
2453 }
2454 
vfio_iommu_type1_detach_group(void * iommu_data,struct iommu_group * iommu_group)2455 static void vfio_iommu_type1_detach_group(void *iommu_data,
2456 					  struct iommu_group *iommu_group)
2457 {
2458 	struct vfio_iommu *iommu = iommu_data;
2459 	struct vfio_domain *domain;
2460 	struct vfio_iommu_group *group;
2461 	bool update_dirty_scope = false;
2462 	LIST_HEAD(iova_copy);
2463 
2464 	mutex_lock(&iommu->lock);
2465 	list_for_each_entry(group, &iommu->emulated_iommu_groups, next) {
2466 		if (group->iommu_group != iommu_group)
2467 			continue;
2468 		update_dirty_scope = !group->pinned_page_dirty_scope;
2469 		list_del(&group->next);
2470 		kfree(group);
2471 
2472 		if (list_empty(&iommu->emulated_iommu_groups) &&
2473 		    list_empty(&iommu->domain_list)) {
2474 			WARN_ON(!list_empty(&iommu->device_list));
2475 			vfio_iommu_unmap_unpin_all(iommu);
2476 		}
2477 		goto detach_group_done;
2478 	}
2479 
2480 	/*
2481 	 * Get a copy of iova list. This will be used to update
2482 	 * and to replace the current one later. Please note that
2483 	 * we will leave the original list as it is if update fails.
2484 	 */
2485 	vfio_iommu_iova_get_copy(iommu, &iova_copy);
2486 
2487 	list_for_each_entry(domain, &iommu->domain_list, next) {
2488 		group = find_iommu_group(domain, iommu_group);
2489 		if (!group)
2490 			continue;
2491 
2492 		iommu_detach_group(domain->domain, group->iommu_group);
2493 		update_dirty_scope = !group->pinned_page_dirty_scope;
2494 		list_del(&group->next);
2495 		kfree(group);
2496 		/*
2497 		 * Group ownership provides privilege, if the group list is
2498 		 * empty, the domain goes away. If it's the last domain with
2499 		 * iommu and external domain doesn't exist, then all the
2500 		 * mappings go away too. If it's the last domain with iommu and
2501 		 * external domain exist, update accounting
2502 		 */
2503 		if (list_empty(&domain->group_list)) {
2504 			if (list_is_singular(&iommu->domain_list)) {
2505 				if (list_empty(&iommu->emulated_iommu_groups)) {
2506 					WARN_ON(!list_empty(
2507 						&iommu->device_list));
2508 					vfio_iommu_unmap_unpin_all(iommu);
2509 				} else {
2510 					vfio_iommu_unmap_unpin_reaccount(iommu);
2511 				}
2512 			}
2513 			iommu_domain_free(domain->domain);
2514 			list_del(&domain->next);
2515 			kfree(domain);
2516 			vfio_iommu_aper_expand(iommu, &iova_copy);
2517 			vfio_update_pgsize_bitmap(iommu);
2518 		}
2519 		break;
2520 	}
2521 
2522 	if (!vfio_iommu_resv_refresh(iommu, &iova_copy))
2523 		vfio_iommu_iova_insert_copy(iommu, &iova_copy);
2524 	else
2525 		vfio_iommu_iova_free(&iova_copy);
2526 
2527 detach_group_done:
2528 	/*
2529 	 * Removal of a group without dirty tracking may allow the iommu scope
2530 	 * to be promoted.
2531 	 */
2532 	if (update_dirty_scope) {
2533 		iommu->num_non_pinned_groups--;
2534 		if (iommu->dirty_page_tracking)
2535 			vfio_iommu_populate_bitmap_full(iommu);
2536 	}
2537 	mutex_unlock(&iommu->lock);
2538 }
2539 
vfio_iommu_type1_open(unsigned long arg)2540 static void *vfio_iommu_type1_open(unsigned long arg)
2541 {
2542 	struct vfio_iommu *iommu;
2543 
2544 	iommu = kzalloc(sizeof(*iommu), GFP_KERNEL);
2545 	if (!iommu)
2546 		return ERR_PTR(-ENOMEM);
2547 
2548 	switch (arg) {
2549 	case VFIO_TYPE1_IOMMU:
2550 		break;
2551 	case VFIO_TYPE1_NESTING_IOMMU:
2552 		iommu->nesting = true;
2553 		fallthrough;
2554 	case VFIO_TYPE1v2_IOMMU:
2555 		iommu->v2 = true;
2556 		break;
2557 	default:
2558 		kfree(iommu);
2559 		return ERR_PTR(-EINVAL);
2560 	}
2561 
2562 	INIT_LIST_HEAD(&iommu->domain_list);
2563 	INIT_LIST_HEAD(&iommu->iova_list);
2564 	iommu->dma_list = RB_ROOT;
2565 	iommu->dma_avail = dma_entry_limit;
2566 	mutex_init(&iommu->lock);
2567 	mutex_init(&iommu->device_list_lock);
2568 	INIT_LIST_HEAD(&iommu->device_list);
2569 	iommu->pgsize_bitmap = PAGE_MASK;
2570 	INIT_LIST_HEAD(&iommu->emulated_iommu_groups);
2571 
2572 	return iommu;
2573 }
2574 
vfio_release_domain(struct vfio_domain * domain)2575 static void vfio_release_domain(struct vfio_domain *domain)
2576 {
2577 	struct vfio_iommu_group *group, *group_tmp;
2578 
2579 	list_for_each_entry_safe(group, group_tmp,
2580 				 &domain->group_list, next) {
2581 		iommu_detach_group(domain->domain, group->iommu_group);
2582 		list_del(&group->next);
2583 		kfree(group);
2584 	}
2585 
2586 	iommu_domain_free(domain->domain);
2587 }
2588 
vfio_iommu_type1_release(void * iommu_data)2589 static void vfio_iommu_type1_release(void *iommu_data)
2590 {
2591 	struct vfio_iommu *iommu = iommu_data;
2592 	struct vfio_domain *domain, *domain_tmp;
2593 	struct vfio_iommu_group *group, *next_group;
2594 
2595 	list_for_each_entry_safe(group, next_group,
2596 			&iommu->emulated_iommu_groups, next) {
2597 		list_del(&group->next);
2598 		kfree(group);
2599 	}
2600 
2601 	vfio_iommu_unmap_unpin_all(iommu);
2602 
2603 	list_for_each_entry_safe(domain, domain_tmp,
2604 				 &iommu->domain_list, next) {
2605 		vfio_release_domain(domain);
2606 		list_del(&domain->next);
2607 		kfree(domain);
2608 	}
2609 
2610 	vfio_iommu_iova_free(&iommu->iova_list);
2611 
2612 	kfree(iommu);
2613 }
2614 
vfio_domains_have_enforce_cache_coherency(struct vfio_iommu * iommu)2615 static int vfio_domains_have_enforce_cache_coherency(struct vfio_iommu *iommu)
2616 {
2617 	struct vfio_domain *domain;
2618 	int ret = 1;
2619 
2620 	mutex_lock(&iommu->lock);
2621 	list_for_each_entry(domain, &iommu->domain_list, next) {
2622 		if (!(domain->enforce_cache_coherency)) {
2623 			ret = 0;
2624 			break;
2625 		}
2626 	}
2627 	mutex_unlock(&iommu->lock);
2628 
2629 	return ret;
2630 }
2631 
vfio_iommu_has_emulated(struct vfio_iommu * iommu)2632 static bool vfio_iommu_has_emulated(struct vfio_iommu *iommu)
2633 {
2634 	bool ret;
2635 
2636 	mutex_lock(&iommu->lock);
2637 	ret = !list_empty(&iommu->emulated_iommu_groups);
2638 	mutex_unlock(&iommu->lock);
2639 	return ret;
2640 }
2641 
vfio_iommu_type1_check_extension(struct vfio_iommu * iommu,unsigned long arg)2642 static int vfio_iommu_type1_check_extension(struct vfio_iommu *iommu,
2643 					    unsigned long arg)
2644 {
2645 	switch (arg) {
2646 	case VFIO_TYPE1_IOMMU:
2647 	case VFIO_TYPE1v2_IOMMU:
2648 	case VFIO_TYPE1_NESTING_IOMMU:
2649 	case VFIO_UNMAP_ALL:
2650 		return 1;
2651 	case VFIO_UPDATE_VADDR:
2652 		/*
2653 		 * Disable this feature if mdevs are present.  They cannot
2654 		 * safely pin/unpin/rw while vaddrs are being updated.
2655 		 */
2656 		return iommu && !vfio_iommu_has_emulated(iommu);
2657 	case VFIO_DMA_CC_IOMMU:
2658 		if (!iommu)
2659 			return 0;
2660 		return vfio_domains_have_enforce_cache_coherency(iommu);
2661 	default:
2662 		return 0;
2663 	}
2664 }
2665 
vfio_iommu_iova_add_cap(struct vfio_info_cap * caps,struct vfio_iommu_type1_info_cap_iova_range * cap_iovas,size_t size)2666 static int vfio_iommu_iova_add_cap(struct vfio_info_cap *caps,
2667 		 struct vfio_iommu_type1_info_cap_iova_range *cap_iovas,
2668 		 size_t size)
2669 {
2670 	struct vfio_info_cap_header *header;
2671 	struct vfio_iommu_type1_info_cap_iova_range *iova_cap;
2672 
2673 	header = vfio_info_cap_add(caps, size,
2674 				   VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE, 1);
2675 	if (IS_ERR(header))
2676 		return PTR_ERR(header);
2677 
2678 	iova_cap = container_of(header,
2679 				struct vfio_iommu_type1_info_cap_iova_range,
2680 				header);
2681 	iova_cap->nr_iovas = cap_iovas->nr_iovas;
2682 	memcpy(iova_cap->iova_ranges, cap_iovas->iova_ranges,
2683 	       cap_iovas->nr_iovas * sizeof(*cap_iovas->iova_ranges));
2684 	return 0;
2685 }
2686 
vfio_iommu_iova_build_caps(struct vfio_iommu * iommu,struct vfio_info_cap * caps)2687 static int vfio_iommu_iova_build_caps(struct vfio_iommu *iommu,
2688 				      struct vfio_info_cap *caps)
2689 {
2690 	struct vfio_iommu_type1_info_cap_iova_range *cap_iovas;
2691 	struct vfio_iova *iova;
2692 	size_t size;
2693 	int iovas = 0, i = 0, ret;
2694 
2695 	list_for_each_entry(iova, &iommu->iova_list, list)
2696 		iovas++;
2697 
2698 	if (!iovas) {
2699 		/*
2700 		 * Return 0 as a container with a single mdev device
2701 		 * will have an empty list
2702 		 */
2703 		return 0;
2704 	}
2705 
2706 	size = struct_size(cap_iovas, iova_ranges, iovas);
2707 
2708 	cap_iovas = kzalloc(size, GFP_KERNEL);
2709 	if (!cap_iovas)
2710 		return -ENOMEM;
2711 
2712 	cap_iovas->nr_iovas = iovas;
2713 
2714 	list_for_each_entry(iova, &iommu->iova_list, list) {
2715 		cap_iovas->iova_ranges[i].start = iova->start;
2716 		cap_iovas->iova_ranges[i].end = iova->end;
2717 		i++;
2718 	}
2719 
2720 	ret = vfio_iommu_iova_add_cap(caps, cap_iovas, size);
2721 
2722 	kfree(cap_iovas);
2723 	return ret;
2724 }
2725 
vfio_iommu_migration_build_caps(struct vfio_iommu * iommu,struct vfio_info_cap * caps)2726 static int vfio_iommu_migration_build_caps(struct vfio_iommu *iommu,
2727 					   struct vfio_info_cap *caps)
2728 {
2729 	struct vfio_iommu_type1_info_cap_migration cap_mig = {};
2730 
2731 	cap_mig.header.id = VFIO_IOMMU_TYPE1_INFO_CAP_MIGRATION;
2732 	cap_mig.header.version = 1;
2733 
2734 	cap_mig.flags = 0;
2735 	/* support minimum pgsize */
2736 	cap_mig.pgsize_bitmap = (size_t)1 << __ffs(iommu->pgsize_bitmap);
2737 	cap_mig.max_dirty_bitmap_size = DIRTY_BITMAP_SIZE_MAX;
2738 
2739 	return vfio_info_add_capability(caps, &cap_mig.header, sizeof(cap_mig));
2740 }
2741 
vfio_iommu_dma_avail_build_caps(struct vfio_iommu * iommu,struct vfio_info_cap * caps)2742 static int vfio_iommu_dma_avail_build_caps(struct vfio_iommu *iommu,
2743 					   struct vfio_info_cap *caps)
2744 {
2745 	struct vfio_iommu_type1_info_dma_avail cap_dma_avail;
2746 
2747 	cap_dma_avail.header.id = VFIO_IOMMU_TYPE1_INFO_DMA_AVAIL;
2748 	cap_dma_avail.header.version = 1;
2749 
2750 	cap_dma_avail.avail = iommu->dma_avail;
2751 
2752 	return vfio_info_add_capability(caps, &cap_dma_avail.header,
2753 					sizeof(cap_dma_avail));
2754 }
2755 
vfio_iommu_type1_get_info(struct vfio_iommu * iommu,unsigned long arg)2756 static int vfio_iommu_type1_get_info(struct vfio_iommu *iommu,
2757 				     unsigned long arg)
2758 {
2759 	struct vfio_iommu_type1_info info = {};
2760 	unsigned long minsz;
2761 	struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
2762 	int ret;
2763 
2764 	minsz = offsetofend(struct vfio_iommu_type1_info, iova_pgsizes);
2765 
2766 	if (copy_from_user(&info, (void __user *)arg, minsz))
2767 		return -EFAULT;
2768 
2769 	if (info.argsz < minsz)
2770 		return -EINVAL;
2771 
2772 	minsz = min_t(size_t, info.argsz, sizeof(info));
2773 
2774 	mutex_lock(&iommu->lock);
2775 	info.flags = VFIO_IOMMU_INFO_PGSIZES;
2776 
2777 	info.iova_pgsizes = iommu->pgsize_bitmap;
2778 
2779 	ret = vfio_iommu_migration_build_caps(iommu, &caps);
2780 
2781 	if (!ret)
2782 		ret = vfio_iommu_dma_avail_build_caps(iommu, &caps);
2783 
2784 	if (!ret)
2785 		ret = vfio_iommu_iova_build_caps(iommu, &caps);
2786 
2787 	mutex_unlock(&iommu->lock);
2788 
2789 	if (ret)
2790 		return ret;
2791 
2792 	if (caps.size) {
2793 		info.flags |= VFIO_IOMMU_INFO_CAPS;
2794 
2795 		if (info.argsz < sizeof(info) + caps.size) {
2796 			info.argsz = sizeof(info) + caps.size;
2797 		} else {
2798 			vfio_info_cap_shift(&caps, sizeof(info));
2799 			if (copy_to_user((void __user *)arg +
2800 					sizeof(info), caps.buf,
2801 					caps.size)) {
2802 				kfree(caps.buf);
2803 				return -EFAULT;
2804 			}
2805 			info.cap_offset = sizeof(info);
2806 		}
2807 
2808 		kfree(caps.buf);
2809 	}
2810 
2811 	return copy_to_user((void __user *)arg, &info, minsz) ?
2812 			-EFAULT : 0;
2813 }
2814 
vfio_iommu_type1_map_dma(struct vfio_iommu * iommu,unsigned long arg)2815 static int vfio_iommu_type1_map_dma(struct vfio_iommu *iommu,
2816 				    unsigned long arg)
2817 {
2818 	struct vfio_iommu_type1_dma_map map;
2819 	unsigned long minsz;
2820 	uint32_t mask = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE |
2821 			VFIO_DMA_MAP_FLAG_VADDR;
2822 
2823 	minsz = offsetofend(struct vfio_iommu_type1_dma_map, size);
2824 
2825 	if (copy_from_user(&map, (void __user *)arg, minsz))
2826 		return -EFAULT;
2827 
2828 	if (map.argsz < minsz || map.flags & ~mask)
2829 		return -EINVAL;
2830 
2831 	return vfio_dma_do_map(iommu, &map);
2832 }
2833 
vfio_iommu_type1_unmap_dma(struct vfio_iommu * iommu,unsigned long arg)2834 static int vfio_iommu_type1_unmap_dma(struct vfio_iommu *iommu,
2835 				      unsigned long arg)
2836 {
2837 	struct vfio_iommu_type1_dma_unmap unmap;
2838 	struct vfio_bitmap bitmap = { 0 };
2839 	uint32_t mask = VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP |
2840 			VFIO_DMA_UNMAP_FLAG_VADDR |
2841 			VFIO_DMA_UNMAP_FLAG_ALL;
2842 	unsigned long minsz;
2843 	int ret;
2844 
2845 	minsz = offsetofend(struct vfio_iommu_type1_dma_unmap, size);
2846 
2847 	if (copy_from_user(&unmap, (void __user *)arg, minsz))
2848 		return -EFAULT;
2849 
2850 	if (unmap.argsz < minsz || unmap.flags & ~mask)
2851 		return -EINVAL;
2852 
2853 	if ((unmap.flags & VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP) &&
2854 	    (unmap.flags & (VFIO_DMA_UNMAP_FLAG_ALL |
2855 			    VFIO_DMA_UNMAP_FLAG_VADDR)))
2856 		return -EINVAL;
2857 
2858 	if (unmap.flags & VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP) {
2859 		unsigned long pgshift;
2860 
2861 		if (unmap.argsz < (minsz + sizeof(bitmap)))
2862 			return -EINVAL;
2863 
2864 		if (copy_from_user(&bitmap,
2865 				   (void __user *)(arg + minsz),
2866 				   sizeof(bitmap)))
2867 			return -EFAULT;
2868 
2869 		if (!access_ok((void __user *)bitmap.data, bitmap.size))
2870 			return -EINVAL;
2871 
2872 		pgshift = __ffs(bitmap.pgsize);
2873 		ret = verify_bitmap_size(unmap.size >> pgshift,
2874 					 bitmap.size);
2875 		if (ret)
2876 			return ret;
2877 	}
2878 
2879 	ret = vfio_dma_do_unmap(iommu, &unmap, &bitmap);
2880 	if (ret)
2881 		return ret;
2882 
2883 	return copy_to_user((void __user *)arg, &unmap, minsz) ?
2884 			-EFAULT : 0;
2885 }
2886 
vfio_iommu_type1_dirty_pages(struct vfio_iommu * iommu,unsigned long arg)2887 static int vfio_iommu_type1_dirty_pages(struct vfio_iommu *iommu,
2888 					unsigned long arg)
2889 {
2890 	struct vfio_iommu_type1_dirty_bitmap dirty;
2891 	uint32_t mask = VFIO_IOMMU_DIRTY_PAGES_FLAG_START |
2892 			VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP |
2893 			VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
2894 	unsigned long minsz;
2895 	int ret = 0;
2896 
2897 	if (!iommu->v2)
2898 		return -EACCES;
2899 
2900 	minsz = offsetofend(struct vfio_iommu_type1_dirty_bitmap, flags);
2901 
2902 	if (copy_from_user(&dirty, (void __user *)arg, minsz))
2903 		return -EFAULT;
2904 
2905 	if (dirty.argsz < minsz || dirty.flags & ~mask)
2906 		return -EINVAL;
2907 
2908 	/* only one flag should be set at a time */
2909 	if (__ffs(dirty.flags) != __fls(dirty.flags))
2910 		return -EINVAL;
2911 
2912 	if (dirty.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_START) {
2913 		size_t pgsize;
2914 
2915 		mutex_lock(&iommu->lock);
2916 		pgsize = 1 << __ffs(iommu->pgsize_bitmap);
2917 		if (!iommu->dirty_page_tracking) {
2918 			ret = vfio_dma_bitmap_alloc_all(iommu, pgsize);
2919 			if (!ret)
2920 				iommu->dirty_page_tracking = true;
2921 		}
2922 		mutex_unlock(&iommu->lock);
2923 		return ret;
2924 	} else if (dirty.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP) {
2925 		mutex_lock(&iommu->lock);
2926 		if (iommu->dirty_page_tracking) {
2927 			iommu->dirty_page_tracking = false;
2928 			vfio_dma_bitmap_free_all(iommu);
2929 		}
2930 		mutex_unlock(&iommu->lock);
2931 		return 0;
2932 	} else if (dirty.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP) {
2933 		struct vfio_iommu_type1_dirty_bitmap_get range;
2934 		unsigned long pgshift;
2935 		size_t data_size = dirty.argsz - minsz;
2936 		size_t iommu_pgsize;
2937 
2938 		if (!data_size || data_size < sizeof(range))
2939 			return -EINVAL;
2940 
2941 		if (copy_from_user(&range, (void __user *)(arg + minsz),
2942 				   sizeof(range)))
2943 			return -EFAULT;
2944 
2945 		if (range.iova + range.size < range.iova)
2946 			return -EINVAL;
2947 		if (!access_ok((void __user *)range.bitmap.data,
2948 			       range.bitmap.size))
2949 			return -EINVAL;
2950 
2951 		pgshift = __ffs(range.bitmap.pgsize);
2952 		ret = verify_bitmap_size(range.size >> pgshift,
2953 					 range.bitmap.size);
2954 		if (ret)
2955 			return ret;
2956 
2957 		mutex_lock(&iommu->lock);
2958 
2959 		iommu_pgsize = (size_t)1 << __ffs(iommu->pgsize_bitmap);
2960 
2961 		/* allow only smallest supported pgsize */
2962 		if (range.bitmap.pgsize != iommu_pgsize) {
2963 			ret = -EINVAL;
2964 			goto out_unlock;
2965 		}
2966 		if (range.iova & (iommu_pgsize - 1)) {
2967 			ret = -EINVAL;
2968 			goto out_unlock;
2969 		}
2970 		if (!range.size || range.size & (iommu_pgsize - 1)) {
2971 			ret = -EINVAL;
2972 			goto out_unlock;
2973 		}
2974 
2975 		if (iommu->dirty_page_tracking)
2976 			ret = vfio_iova_dirty_bitmap(range.bitmap.data,
2977 						     iommu, range.iova,
2978 						     range.size,
2979 						     range.bitmap.pgsize);
2980 		else
2981 			ret = -EINVAL;
2982 out_unlock:
2983 		mutex_unlock(&iommu->lock);
2984 
2985 		return ret;
2986 	}
2987 
2988 	return -EINVAL;
2989 }
2990 
vfio_iommu_type1_ioctl(void * iommu_data,unsigned int cmd,unsigned long arg)2991 static long vfio_iommu_type1_ioctl(void *iommu_data,
2992 				   unsigned int cmd, unsigned long arg)
2993 {
2994 	struct vfio_iommu *iommu = iommu_data;
2995 
2996 	switch (cmd) {
2997 	case VFIO_CHECK_EXTENSION:
2998 		return vfio_iommu_type1_check_extension(iommu, arg);
2999 	case VFIO_IOMMU_GET_INFO:
3000 		return vfio_iommu_type1_get_info(iommu, arg);
3001 	case VFIO_IOMMU_MAP_DMA:
3002 		return vfio_iommu_type1_map_dma(iommu, arg);
3003 	case VFIO_IOMMU_UNMAP_DMA:
3004 		return vfio_iommu_type1_unmap_dma(iommu, arg);
3005 	case VFIO_IOMMU_DIRTY_PAGES:
3006 		return vfio_iommu_type1_dirty_pages(iommu, arg);
3007 	default:
3008 		return -ENOTTY;
3009 	}
3010 }
3011 
vfio_iommu_type1_register_device(void * iommu_data,struct vfio_device * vdev)3012 static void vfio_iommu_type1_register_device(void *iommu_data,
3013 					     struct vfio_device *vdev)
3014 {
3015 	struct vfio_iommu *iommu = iommu_data;
3016 
3017 	if (!vdev->ops->dma_unmap)
3018 		return;
3019 
3020 	/*
3021 	 * list_empty(&iommu->device_list) is tested under the iommu->lock while
3022 	 * iteration for dma_unmap must be done under the device_list_lock.
3023 	 * Holding both locks here allows avoiding the device_list_lock in
3024 	 * several fast paths. See vfio_notify_dma_unmap()
3025 	 */
3026 	mutex_lock(&iommu->lock);
3027 	mutex_lock(&iommu->device_list_lock);
3028 	list_add(&vdev->iommu_entry, &iommu->device_list);
3029 	mutex_unlock(&iommu->device_list_lock);
3030 	mutex_unlock(&iommu->lock);
3031 }
3032 
vfio_iommu_type1_unregister_device(void * iommu_data,struct vfio_device * vdev)3033 static void vfio_iommu_type1_unregister_device(void *iommu_data,
3034 					       struct vfio_device *vdev)
3035 {
3036 	struct vfio_iommu *iommu = iommu_data;
3037 
3038 	if (!vdev->ops->dma_unmap)
3039 		return;
3040 
3041 	mutex_lock(&iommu->lock);
3042 	mutex_lock(&iommu->device_list_lock);
3043 	list_del(&vdev->iommu_entry);
3044 	mutex_unlock(&iommu->device_list_lock);
3045 	mutex_unlock(&iommu->lock);
3046 }
3047 
vfio_iommu_type1_dma_rw_chunk(struct vfio_iommu * iommu,dma_addr_t user_iova,void * data,size_t count,bool write,size_t * copied)3048 static int vfio_iommu_type1_dma_rw_chunk(struct vfio_iommu *iommu,
3049 					 dma_addr_t user_iova, void *data,
3050 					 size_t count, bool write,
3051 					 size_t *copied)
3052 {
3053 	struct mm_struct *mm;
3054 	unsigned long vaddr;
3055 	struct vfio_dma *dma;
3056 	bool kthread = current->mm == NULL;
3057 	size_t offset;
3058 
3059 	*copied = 0;
3060 
3061 	dma = vfio_find_dma(iommu, user_iova, 1);
3062 	if (!dma)
3063 		return -EINVAL;
3064 
3065 	if ((write && !(dma->prot & IOMMU_WRITE)) ||
3066 			!(dma->prot & IOMMU_READ))
3067 		return -EPERM;
3068 
3069 	mm = dma->mm;
3070 	if (!mmget_not_zero(mm))
3071 		return -EPERM;
3072 
3073 	if (kthread)
3074 		kthread_use_mm(mm);
3075 	else if (current->mm != mm)
3076 		goto out;
3077 
3078 	offset = user_iova - dma->iova;
3079 
3080 	if (count > dma->size - offset)
3081 		count = dma->size - offset;
3082 
3083 	vaddr = dma->vaddr + offset;
3084 
3085 	if (write) {
3086 		*copied = copy_to_user((void __user *)vaddr, data,
3087 					 count) ? 0 : count;
3088 		if (*copied && iommu->dirty_page_tracking) {
3089 			unsigned long pgshift = __ffs(iommu->pgsize_bitmap);
3090 			/*
3091 			 * Bitmap populated with the smallest supported page
3092 			 * size
3093 			 */
3094 			bitmap_set(dma->bitmap, offset >> pgshift,
3095 				   ((offset + *copied - 1) >> pgshift) -
3096 				   (offset >> pgshift) + 1);
3097 		}
3098 	} else
3099 		*copied = copy_from_user(data, (void __user *)vaddr,
3100 					   count) ? 0 : count;
3101 	if (kthread)
3102 		kthread_unuse_mm(mm);
3103 out:
3104 	mmput(mm);
3105 	return *copied ? 0 : -EFAULT;
3106 }
3107 
vfio_iommu_type1_dma_rw(void * iommu_data,dma_addr_t user_iova,void * data,size_t count,bool write)3108 static int vfio_iommu_type1_dma_rw(void *iommu_data, dma_addr_t user_iova,
3109 				   void *data, size_t count, bool write)
3110 {
3111 	struct vfio_iommu *iommu = iommu_data;
3112 	int ret = 0;
3113 	size_t done;
3114 
3115 	mutex_lock(&iommu->lock);
3116 
3117 	if (WARN_ONCE(iommu->vaddr_invalid_count,
3118 		      "vfio_dma_rw not allowed with VFIO_UPDATE_VADDR\n")) {
3119 		ret = -EBUSY;
3120 		goto out;
3121 	}
3122 
3123 	while (count > 0) {
3124 		ret = vfio_iommu_type1_dma_rw_chunk(iommu, user_iova, data,
3125 						    count, write, &done);
3126 		if (ret)
3127 			break;
3128 
3129 		count -= done;
3130 		data += done;
3131 		user_iova += done;
3132 	}
3133 
3134 out:
3135 	mutex_unlock(&iommu->lock);
3136 	return ret;
3137 }
3138 
3139 static struct iommu_domain *
vfio_iommu_type1_group_iommu_domain(void * iommu_data,struct iommu_group * iommu_group)3140 vfio_iommu_type1_group_iommu_domain(void *iommu_data,
3141 				    struct iommu_group *iommu_group)
3142 {
3143 	struct iommu_domain *domain = ERR_PTR(-ENODEV);
3144 	struct vfio_iommu *iommu = iommu_data;
3145 	struct vfio_domain *d;
3146 
3147 	if (!iommu || !iommu_group)
3148 		return ERR_PTR(-EINVAL);
3149 
3150 	mutex_lock(&iommu->lock);
3151 	list_for_each_entry(d, &iommu->domain_list, next) {
3152 		if (find_iommu_group(d, iommu_group)) {
3153 			domain = d->domain;
3154 			break;
3155 		}
3156 	}
3157 	mutex_unlock(&iommu->lock);
3158 
3159 	return domain;
3160 }
3161 
3162 static const struct vfio_iommu_driver_ops vfio_iommu_driver_ops_type1 = {
3163 	.name			= "vfio-iommu-type1",
3164 	.owner			= THIS_MODULE,
3165 	.open			= vfio_iommu_type1_open,
3166 	.release		= vfio_iommu_type1_release,
3167 	.ioctl			= vfio_iommu_type1_ioctl,
3168 	.attach_group		= vfio_iommu_type1_attach_group,
3169 	.detach_group		= vfio_iommu_type1_detach_group,
3170 	.pin_pages		= vfio_iommu_type1_pin_pages,
3171 	.unpin_pages		= vfio_iommu_type1_unpin_pages,
3172 	.register_device	= vfio_iommu_type1_register_device,
3173 	.unregister_device	= vfio_iommu_type1_unregister_device,
3174 	.dma_rw			= vfio_iommu_type1_dma_rw,
3175 	.group_iommu_domain	= vfio_iommu_type1_group_iommu_domain,
3176 };
3177 
vfio_iommu_type1_init(void)3178 static int __init vfio_iommu_type1_init(void)
3179 {
3180 	return vfio_register_iommu_driver(&vfio_iommu_driver_ops_type1);
3181 }
3182 
vfio_iommu_type1_cleanup(void)3183 static void __exit vfio_iommu_type1_cleanup(void)
3184 {
3185 	vfio_unregister_iommu_driver(&vfio_iommu_driver_ops_type1);
3186 }
3187 
3188 module_init(vfio_iommu_type1_init);
3189 module_exit(vfio_iommu_type1_cleanup);
3190 
3191 MODULE_VERSION(DRIVER_VERSION);
3192 MODULE_LICENSE("GPL v2");
3193 MODULE_AUTHOR(DRIVER_AUTHOR);
3194 MODULE_DESCRIPTION(DRIVER_DESC);
3195