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