]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blob - drivers/vfio/vfio_iommu_type1.c
Merge tag 'armsoc-dt' of git://git.kernel.org/pub/scm/linux/kernel/git/soc/soc
[mirror_ubuntu-hirsute-kernel.git] / drivers / vfio / vfio_iommu_type1.c
1 /*
2 * VFIO: IOMMU DMA mapping support for Type1 IOMMU
3 *
4 * Copyright (C) 2012 Red Hat, Inc. All rights reserved.
5 * Author: Alex Williamson <alex.williamson@redhat.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
10 *
11 * Derived from original vfio:
12 * Copyright 2010 Cisco Systems, Inc. All rights reserved.
13 * Author: Tom Lyon, pugs@cisco.com
14 *
15 * We arbitrarily define a Type1 IOMMU as one matching the below code.
16 * It could be called the x86 IOMMU as it's designed for AMD-Vi & Intel
17 * VT-d, but that makes it harder to re-use as theoretically anyone
18 * implementing a similar IOMMU could make use of this. We expect the
19 * IOMMU to support the IOMMU API and have few to no restrictions around
20 * the IOVA range that can be mapped. The Type1 IOMMU is currently
21 * optimized for relatively static mappings of a userspace process with
22 * userpsace pages pinned into memory. We also assume devices and IOMMU
23 * domains are PCI based as the IOMMU API is still centered around a
24 * device/bus interface rather than a group interface.
25 */
26
27 #include <linux/compat.h>
28 #include <linux/device.h>
29 #include <linux/fs.h>
30 #include <linux/iommu.h>
31 #include <linux/module.h>
32 #include <linux/mm.h>
33 #include <linux/rbtree.h>
34 #include <linux/sched/signal.h>
35 #include <linux/sched/mm.h>
36 #include <linux/slab.h>
37 #include <linux/uaccess.h>
38 #include <linux/vfio.h>
39 #include <linux/workqueue.h>
40 #include <linux/mdev.h>
41 #include <linux/notifier.h>
42 #include <linux/dma-iommu.h>
43 #include <linux/irqdomain.h>
44
45 #define DRIVER_VERSION "0.2"
46 #define DRIVER_AUTHOR "Alex Williamson <alex.williamson@redhat.com>"
47 #define DRIVER_DESC "Type1 IOMMU driver for VFIO"
48
49 static bool allow_unsafe_interrupts;
50 module_param_named(allow_unsafe_interrupts,
51 allow_unsafe_interrupts, bool, S_IRUGO | S_IWUSR);
52 MODULE_PARM_DESC(allow_unsafe_interrupts,
53 "Enable VFIO IOMMU support for on platforms without interrupt remapping support.");
54
55 static bool disable_hugepages;
56 module_param_named(disable_hugepages,
57 disable_hugepages, bool, S_IRUGO | S_IWUSR);
58 MODULE_PARM_DESC(disable_hugepages,
59 "Disable VFIO IOMMU support for IOMMU hugepages.");
60
61 static unsigned int dma_entry_limit __read_mostly = U16_MAX;
62 module_param_named(dma_entry_limit, dma_entry_limit, uint, 0644);
63 MODULE_PARM_DESC(dma_entry_limit,
64 "Maximum number of user DMA mappings per container (65535).");
65
66 struct vfio_iommu {
67 struct list_head domain_list;
68 struct vfio_domain *external_domain; /* domain for external user */
69 struct mutex lock;
70 struct rb_root dma_list;
71 struct blocking_notifier_head notifier;
72 unsigned int dma_avail;
73 bool v2;
74 bool nesting;
75 };
76
77 struct vfio_domain {
78 struct iommu_domain *domain;
79 struct list_head next;
80 struct list_head group_list;
81 int prot; /* IOMMU_CACHE */
82 bool fgsp; /* Fine-grained super pages */
83 };
84
85 struct vfio_dma {
86 struct rb_node node;
87 dma_addr_t iova; /* Device address */
88 unsigned long vaddr; /* Process virtual addr */
89 size_t size; /* Map size (bytes) */
90 int prot; /* IOMMU_READ/WRITE */
91 bool iommu_mapped;
92 bool lock_cap; /* capable(CAP_IPC_LOCK) */
93 struct task_struct *task;
94 struct rb_root pfn_list; /* Ex-user pinned pfn list */
95 };
96
97 struct vfio_group {
98 struct iommu_group *iommu_group;
99 struct list_head next;
100 bool mdev_group; /* An mdev group */
101 };
102
103 /*
104 * Guest RAM pinning working set or DMA target
105 */
106 struct vfio_pfn {
107 struct rb_node node;
108 dma_addr_t iova; /* Device address */
109 unsigned long pfn; /* Host pfn */
110 atomic_t ref_count;
111 };
112
113 struct vfio_regions {
114 struct list_head list;
115 dma_addr_t iova;
116 phys_addr_t phys;
117 size_t len;
118 };
119
120 #define IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu) \
121 (!list_empty(&iommu->domain_list))
122
123 static int put_pfn(unsigned long pfn, int prot);
124
125 /*
126 * This code handles mapping and unmapping of user data buffers
127 * into DMA'ble space using the IOMMU
128 */
129
130 static struct vfio_dma *vfio_find_dma(struct vfio_iommu *iommu,
131 dma_addr_t start, size_t size)
132 {
133 struct rb_node *node = iommu->dma_list.rb_node;
134
135 while (node) {
136 struct vfio_dma *dma = rb_entry(node, struct vfio_dma, node);
137
138 if (start + size <= dma->iova)
139 node = node->rb_left;
140 else if (start >= dma->iova + dma->size)
141 node = node->rb_right;
142 else
143 return dma;
144 }
145
146 return NULL;
147 }
148
149 static void vfio_link_dma(struct vfio_iommu *iommu, struct vfio_dma *new)
150 {
151 struct rb_node **link = &iommu->dma_list.rb_node, *parent = NULL;
152 struct vfio_dma *dma;
153
154 while (*link) {
155 parent = *link;
156 dma = rb_entry(parent, struct vfio_dma, node);
157
158 if (new->iova + new->size <= dma->iova)
159 link = &(*link)->rb_left;
160 else
161 link = &(*link)->rb_right;
162 }
163
164 rb_link_node(&new->node, parent, link);
165 rb_insert_color(&new->node, &iommu->dma_list);
166 }
167
168 static void vfio_unlink_dma(struct vfio_iommu *iommu, struct vfio_dma *old)
169 {
170 rb_erase(&old->node, &iommu->dma_list);
171 }
172
173 /*
174 * Helper Functions for host iova-pfn list
175 */
176 static struct vfio_pfn *vfio_find_vpfn(struct vfio_dma *dma, dma_addr_t iova)
177 {
178 struct vfio_pfn *vpfn;
179 struct rb_node *node = dma->pfn_list.rb_node;
180
181 while (node) {
182 vpfn = rb_entry(node, struct vfio_pfn, node);
183
184 if (iova < vpfn->iova)
185 node = node->rb_left;
186 else if (iova > vpfn->iova)
187 node = node->rb_right;
188 else
189 return vpfn;
190 }
191 return NULL;
192 }
193
194 static void vfio_link_pfn(struct vfio_dma *dma,
195 struct vfio_pfn *new)
196 {
197 struct rb_node **link, *parent = NULL;
198 struct vfio_pfn *vpfn;
199
200 link = &dma->pfn_list.rb_node;
201 while (*link) {
202 parent = *link;
203 vpfn = rb_entry(parent, struct vfio_pfn, node);
204
205 if (new->iova < vpfn->iova)
206 link = &(*link)->rb_left;
207 else
208 link = &(*link)->rb_right;
209 }
210
211 rb_link_node(&new->node, parent, link);
212 rb_insert_color(&new->node, &dma->pfn_list);
213 }
214
215 static void vfio_unlink_pfn(struct vfio_dma *dma, struct vfio_pfn *old)
216 {
217 rb_erase(&old->node, &dma->pfn_list);
218 }
219
220 static int vfio_add_to_pfn_list(struct vfio_dma *dma, dma_addr_t iova,
221 unsigned long pfn)
222 {
223 struct vfio_pfn *vpfn;
224
225 vpfn = kzalloc(sizeof(*vpfn), GFP_KERNEL);
226 if (!vpfn)
227 return -ENOMEM;
228
229 vpfn->iova = iova;
230 vpfn->pfn = pfn;
231 atomic_set(&vpfn->ref_count, 1);
232 vfio_link_pfn(dma, vpfn);
233 return 0;
234 }
235
236 static void vfio_remove_from_pfn_list(struct vfio_dma *dma,
237 struct vfio_pfn *vpfn)
238 {
239 vfio_unlink_pfn(dma, vpfn);
240 kfree(vpfn);
241 }
242
243 static struct vfio_pfn *vfio_iova_get_vfio_pfn(struct vfio_dma *dma,
244 unsigned long iova)
245 {
246 struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
247
248 if (vpfn)
249 atomic_inc(&vpfn->ref_count);
250 return vpfn;
251 }
252
253 static int vfio_iova_put_vfio_pfn(struct vfio_dma *dma, struct vfio_pfn *vpfn)
254 {
255 int ret = 0;
256
257 if (atomic_dec_and_test(&vpfn->ref_count)) {
258 ret = put_pfn(vpfn->pfn, dma->prot);
259 vfio_remove_from_pfn_list(dma, vpfn);
260 }
261 return ret;
262 }
263
264 static int vfio_lock_acct(struct vfio_dma *dma, long npage, bool async)
265 {
266 struct mm_struct *mm;
267 int ret;
268
269 if (!npage)
270 return 0;
271
272 mm = async ? get_task_mm(dma->task) : dma->task->mm;
273 if (!mm)
274 return -ESRCH; /* process exited */
275
276 ret = down_write_killable(&mm->mmap_sem);
277 if (!ret) {
278 if (npage > 0) {
279 if (!dma->lock_cap) {
280 unsigned long limit;
281
282 limit = task_rlimit(dma->task,
283 RLIMIT_MEMLOCK) >> PAGE_SHIFT;
284
285 if (mm->locked_vm + npage > limit)
286 ret = -ENOMEM;
287 }
288 }
289
290 if (!ret)
291 mm->locked_vm += npage;
292
293 up_write(&mm->mmap_sem);
294 }
295
296 if (async)
297 mmput(mm);
298
299 return ret;
300 }
301
302 /*
303 * Some mappings aren't backed by a struct page, for example an mmap'd
304 * MMIO range for our own or another device. These use a different
305 * pfn conversion and shouldn't be tracked as locked pages.
306 */
307 static bool is_invalid_reserved_pfn(unsigned long pfn)
308 {
309 if (pfn_valid(pfn)) {
310 bool reserved;
311 struct page *tail = pfn_to_page(pfn);
312 struct page *head = compound_head(tail);
313 reserved = !!(PageReserved(head));
314 if (head != tail) {
315 /*
316 * "head" is not a dangling pointer
317 * (compound_head takes care of that)
318 * but the hugepage may have been split
319 * from under us (and we may not hold a
320 * reference count on the head page so it can
321 * be reused before we run PageReferenced), so
322 * we've to check PageTail before returning
323 * what we just read.
324 */
325 smp_rmb();
326 if (PageTail(tail))
327 return reserved;
328 }
329 return PageReserved(tail);
330 }
331
332 return true;
333 }
334
335 static int put_pfn(unsigned long pfn, int prot)
336 {
337 if (!is_invalid_reserved_pfn(pfn)) {
338 struct page *page = pfn_to_page(pfn);
339 if (prot & IOMMU_WRITE)
340 SetPageDirty(page);
341 put_page(page);
342 return 1;
343 }
344 return 0;
345 }
346
347 static int vaddr_get_pfn(struct mm_struct *mm, unsigned long vaddr,
348 int prot, unsigned long *pfn)
349 {
350 struct page *page[1];
351 struct vm_area_struct *vma;
352 struct vm_area_struct *vmas[1];
353 unsigned int flags = 0;
354 int ret;
355
356 if (prot & IOMMU_WRITE)
357 flags |= FOLL_WRITE;
358
359 down_read(&mm->mmap_sem);
360 if (mm == current->mm) {
361 ret = get_user_pages(vaddr, 1, flags | FOLL_LONGTERM, page,
362 vmas);
363 } else {
364 ret = get_user_pages_remote(NULL, mm, vaddr, 1, flags, page,
365 vmas, NULL);
366 /*
367 * The lifetime of a vaddr_get_pfn() page pin is
368 * userspace-controlled. In the fs-dax case this could
369 * lead to indefinite stalls in filesystem operations.
370 * Disallow attempts to pin fs-dax pages via this
371 * interface.
372 */
373 if (ret > 0 && vma_is_fsdax(vmas[0])) {
374 ret = -EOPNOTSUPP;
375 put_page(page[0]);
376 }
377 }
378 up_read(&mm->mmap_sem);
379
380 if (ret == 1) {
381 *pfn = page_to_pfn(page[0]);
382 return 0;
383 }
384
385 down_read(&mm->mmap_sem);
386
387 vma = find_vma_intersection(mm, vaddr, vaddr + 1);
388
389 if (vma && vma->vm_flags & VM_PFNMAP) {
390 *pfn = ((vaddr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
391 if (is_invalid_reserved_pfn(*pfn))
392 ret = 0;
393 }
394
395 up_read(&mm->mmap_sem);
396 return ret;
397 }
398
399 /*
400 * Attempt to pin pages. We really don't want to track all the pfns and
401 * the iommu can only map chunks of consecutive pfns anyway, so get the
402 * first page and all consecutive pages with the same locking.
403 */
404 static long vfio_pin_pages_remote(struct vfio_dma *dma, unsigned long vaddr,
405 long npage, unsigned long *pfn_base,
406 unsigned long limit)
407 {
408 unsigned long pfn = 0;
409 long ret, pinned = 0, lock_acct = 0;
410 bool rsvd;
411 dma_addr_t iova = vaddr - dma->vaddr + dma->iova;
412
413 /* This code path is only user initiated */
414 if (!current->mm)
415 return -ENODEV;
416
417 ret = vaddr_get_pfn(current->mm, vaddr, dma->prot, pfn_base);
418 if (ret)
419 return ret;
420
421 pinned++;
422 rsvd = is_invalid_reserved_pfn(*pfn_base);
423
424 /*
425 * Reserved pages aren't counted against the user, externally pinned
426 * pages are already counted against the user.
427 */
428 if (!rsvd && !vfio_find_vpfn(dma, iova)) {
429 if (!dma->lock_cap && current->mm->locked_vm + 1 > limit) {
430 put_pfn(*pfn_base, dma->prot);
431 pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n", __func__,
432 limit << PAGE_SHIFT);
433 return -ENOMEM;
434 }
435 lock_acct++;
436 }
437
438 if (unlikely(disable_hugepages))
439 goto out;
440
441 /* Lock all the consecutive pages from pfn_base */
442 for (vaddr += PAGE_SIZE, iova += PAGE_SIZE; pinned < npage;
443 pinned++, vaddr += PAGE_SIZE, iova += PAGE_SIZE) {
444 ret = vaddr_get_pfn(current->mm, vaddr, dma->prot, &pfn);
445 if (ret)
446 break;
447
448 if (pfn != *pfn_base + pinned ||
449 rsvd != is_invalid_reserved_pfn(pfn)) {
450 put_pfn(pfn, dma->prot);
451 break;
452 }
453
454 if (!rsvd && !vfio_find_vpfn(dma, iova)) {
455 if (!dma->lock_cap &&
456 current->mm->locked_vm + lock_acct + 1 > limit) {
457 put_pfn(pfn, dma->prot);
458 pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n",
459 __func__, limit << PAGE_SHIFT);
460 ret = -ENOMEM;
461 goto unpin_out;
462 }
463 lock_acct++;
464 }
465 }
466
467 out:
468 ret = vfio_lock_acct(dma, lock_acct, false);
469
470 unpin_out:
471 if (ret) {
472 if (!rsvd) {
473 for (pfn = *pfn_base ; pinned ; pfn++, pinned--)
474 put_pfn(pfn, dma->prot);
475 }
476
477 return ret;
478 }
479
480 return pinned;
481 }
482
483 static long vfio_unpin_pages_remote(struct vfio_dma *dma, dma_addr_t iova,
484 unsigned long pfn, long npage,
485 bool do_accounting)
486 {
487 long unlocked = 0, locked = 0;
488 long i;
489
490 for (i = 0; i < npage; i++, iova += PAGE_SIZE) {
491 if (put_pfn(pfn++, dma->prot)) {
492 unlocked++;
493 if (vfio_find_vpfn(dma, iova))
494 locked++;
495 }
496 }
497
498 if (do_accounting)
499 vfio_lock_acct(dma, locked - unlocked, true);
500
501 return unlocked;
502 }
503
504 static int vfio_pin_page_external(struct vfio_dma *dma, unsigned long vaddr,
505 unsigned long *pfn_base, bool do_accounting)
506 {
507 struct mm_struct *mm;
508 int ret;
509
510 mm = get_task_mm(dma->task);
511 if (!mm)
512 return -ENODEV;
513
514 ret = vaddr_get_pfn(mm, vaddr, dma->prot, pfn_base);
515 if (!ret && do_accounting && !is_invalid_reserved_pfn(*pfn_base)) {
516 ret = vfio_lock_acct(dma, 1, true);
517 if (ret) {
518 put_pfn(*pfn_base, dma->prot);
519 if (ret == -ENOMEM)
520 pr_warn("%s: Task %s (%d) RLIMIT_MEMLOCK "
521 "(%ld) exceeded\n", __func__,
522 dma->task->comm, task_pid_nr(dma->task),
523 task_rlimit(dma->task, RLIMIT_MEMLOCK));
524 }
525 }
526
527 mmput(mm);
528 return ret;
529 }
530
531 static int vfio_unpin_page_external(struct vfio_dma *dma, dma_addr_t iova,
532 bool do_accounting)
533 {
534 int unlocked;
535 struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
536
537 if (!vpfn)
538 return 0;
539
540 unlocked = vfio_iova_put_vfio_pfn(dma, vpfn);
541
542 if (do_accounting)
543 vfio_lock_acct(dma, -unlocked, true);
544
545 return unlocked;
546 }
547
548 static int vfio_iommu_type1_pin_pages(void *iommu_data,
549 unsigned long *user_pfn,
550 int npage, int prot,
551 unsigned long *phys_pfn)
552 {
553 struct vfio_iommu *iommu = iommu_data;
554 int i, j, ret;
555 unsigned long remote_vaddr;
556 struct vfio_dma *dma;
557 bool do_accounting;
558
559 if (!iommu || !user_pfn || !phys_pfn)
560 return -EINVAL;
561
562 /* Supported for v2 version only */
563 if (!iommu->v2)
564 return -EACCES;
565
566 mutex_lock(&iommu->lock);
567
568 /* Fail if notifier list is empty */
569 if (!iommu->notifier.head) {
570 ret = -EINVAL;
571 goto pin_done;
572 }
573
574 /*
575 * If iommu capable domain exist in the container then all pages are
576 * already pinned and accounted. Accouting should be done if there is no
577 * iommu capable domain in the container.
578 */
579 do_accounting = !IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu);
580
581 for (i = 0; i < npage; i++) {
582 dma_addr_t iova;
583 struct vfio_pfn *vpfn;
584
585 iova = user_pfn[i] << PAGE_SHIFT;
586 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
587 if (!dma) {
588 ret = -EINVAL;
589 goto pin_unwind;
590 }
591
592 if ((dma->prot & prot) != prot) {
593 ret = -EPERM;
594 goto pin_unwind;
595 }
596
597 vpfn = vfio_iova_get_vfio_pfn(dma, iova);
598 if (vpfn) {
599 phys_pfn[i] = vpfn->pfn;
600 continue;
601 }
602
603 remote_vaddr = dma->vaddr + iova - dma->iova;
604 ret = vfio_pin_page_external(dma, remote_vaddr, &phys_pfn[i],
605 do_accounting);
606 if (ret)
607 goto pin_unwind;
608
609 ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
610 if (ret) {
611 vfio_unpin_page_external(dma, iova, do_accounting);
612 goto pin_unwind;
613 }
614 }
615
616 ret = i;
617 goto pin_done;
618
619 pin_unwind:
620 phys_pfn[i] = 0;
621 for (j = 0; j < i; j++) {
622 dma_addr_t iova;
623
624 iova = user_pfn[j] << PAGE_SHIFT;
625 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
626 vfio_unpin_page_external(dma, iova, do_accounting);
627 phys_pfn[j] = 0;
628 }
629 pin_done:
630 mutex_unlock(&iommu->lock);
631 return ret;
632 }
633
634 static int vfio_iommu_type1_unpin_pages(void *iommu_data,
635 unsigned long *user_pfn,
636 int npage)
637 {
638 struct vfio_iommu *iommu = iommu_data;
639 bool do_accounting;
640 int i;
641
642 if (!iommu || !user_pfn)
643 return -EINVAL;
644
645 /* Supported for v2 version only */
646 if (!iommu->v2)
647 return -EACCES;
648
649 mutex_lock(&iommu->lock);
650
651 do_accounting = !IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu);
652 for (i = 0; i < npage; i++) {
653 struct vfio_dma *dma;
654 dma_addr_t iova;
655
656 iova = user_pfn[i] << PAGE_SHIFT;
657 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
658 if (!dma)
659 goto unpin_exit;
660 vfio_unpin_page_external(dma, iova, do_accounting);
661 }
662
663 unpin_exit:
664 mutex_unlock(&iommu->lock);
665 return i > npage ? npage : (i > 0 ? i : -EINVAL);
666 }
667
668 static long vfio_sync_unpin(struct vfio_dma *dma, struct vfio_domain *domain,
669 struct list_head *regions)
670 {
671 long unlocked = 0;
672 struct vfio_regions *entry, *next;
673
674 iommu_tlb_sync(domain->domain);
675
676 list_for_each_entry_safe(entry, next, regions, list) {
677 unlocked += vfio_unpin_pages_remote(dma,
678 entry->iova,
679 entry->phys >> PAGE_SHIFT,
680 entry->len >> PAGE_SHIFT,
681 false);
682 list_del(&entry->list);
683 kfree(entry);
684 }
685
686 cond_resched();
687
688 return unlocked;
689 }
690
691 /*
692 * Generally, VFIO needs to unpin remote pages after each IOTLB flush.
693 * Therefore, when using IOTLB flush sync interface, VFIO need to keep track
694 * of these regions (currently using a list).
695 *
696 * This value specifies maximum number of regions for each IOTLB flush sync.
697 */
698 #define VFIO_IOMMU_TLB_SYNC_MAX 512
699
700 static size_t unmap_unpin_fast(struct vfio_domain *domain,
701 struct vfio_dma *dma, dma_addr_t *iova,
702 size_t len, phys_addr_t phys, long *unlocked,
703 struct list_head *unmapped_list,
704 int *unmapped_cnt)
705 {
706 size_t unmapped = 0;
707 struct vfio_regions *entry = kzalloc(sizeof(*entry), GFP_KERNEL);
708
709 if (entry) {
710 unmapped = iommu_unmap_fast(domain->domain, *iova, len);
711
712 if (!unmapped) {
713 kfree(entry);
714 } else {
715 iommu_tlb_range_add(domain->domain, *iova, unmapped);
716 entry->iova = *iova;
717 entry->phys = phys;
718 entry->len = unmapped;
719 list_add_tail(&entry->list, unmapped_list);
720
721 *iova += unmapped;
722 (*unmapped_cnt)++;
723 }
724 }
725
726 /*
727 * Sync if the number of fast-unmap regions hits the limit
728 * or in case of errors.
729 */
730 if (*unmapped_cnt >= VFIO_IOMMU_TLB_SYNC_MAX || !unmapped) {
731 *unlocked += vfio_sync_unpin(dma, domain,
732 unmapped_list);
733 *unmapped_cnt = 0;
734 }
735
736 return unmapped;
737 }
738
739 static size_t unmap_unpin_slow(struct vfio_domain *domain,
740 struct vfio_dma *dma, dma_addr_t *iova,
741 size_t len, phys_addr_t phys,
742 long *unlocked)
743 {
744 size_t unmapped = iommu_unmap(domain->domain, *iova, len);
745
746 if (unmapped) {
747 *unlocked += vfio_unpin_pages_remote(dma, *iova,
748 phys >> PAGE_SHIFT,
749 unmapped >> PAGE_SHIFT,
750 false);
751 *iova += unmapped;
752 cond_resched();
753 }
754 return unmapped;
755 }
756
757 static long vfio_unmap_unpin(struct vfio_iommu *iommu, struct vfio_dma *dma,
758 bool do_accounting)
759 {
760 dma_addr_t iova = dma->iova, end = dma->iova + dma->size;
761 struct vfio_domain *domain, *d;
762 LIST_HEAD(unmapped_region_list);
763 int unmapped_region_cnt = 0;
764 long unlocked = 0;
765
766 if (!dma->size)
767 return 0;
768
769 if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
770 return 0;
771
772 /*
773 * We use the IOMMU to track the physical addresses, otherwise we'd
774 * need a much more complicated tracking system. Unfortunately that
775 * means we need to use one of the iommu domains to figure out the
776 * pfns to unpin. The rest need to be unmapped in advance so we have
777 * no iommu translations remaining when the pages are unpinned.
778 */
779 domain = d = list_first_entry(&iommu->domain_list,
780 struct vfio_domain, next);
781
782 list_for_each_entry_continue(d, &iommu->domain_list, next) {
783 iommu_unmap(d->domain, dma->iova, dma->size);
784 cond_resched();
785 }
786
787 while (iova < end) {
788 size_t unmapped, len;
789 phys_addr_t phys, next;
790
791 phys = iommu_iova_to_phys(domain->domain, iova);
792 if (WARN_ON(!phys)) {
793 iova += PAGE_SIZE;
794 continue;
795 }
796
797 /*
798 * To optimize for fewer iommu_unmap() calls, each of which
799 * may require hardware cache flushing, try to find the
800 * largest contiguous physical memory chunk to unmap.
801 */
802 for (len = PAGE_SIZE;
803 !domain->fgsp && iova + len < end; len += PAGE_SIZE) {
804 next = iommu_iova_to_phys(domain->domain, iova + len);
805 if (next != phys + len)
806 break;
807 }
808
809 /*
810 * First, try to use fast unmap/unpin. In case of failure,
811 * switch to slow unmap/unpin path.
812 */
813 unmapped = unmap_unpin_fast(domain, dma, &iova, len, phys,
814 &unlocked, &unmapped_region_list,
815 &unmapped_region_cnt);
816 if (!unmapped) {
817 unmapped = unmap_unpin_slow(domain, dma, &iova, len,
818 phys, &unlocked);
819 if (WARN_ON(!unmapped))
820 break;
821 }
822 }
823
824 dma->iommu_mapped = false;
825
826 if (unmapped_region_cnt)
827 unlocked += vfio_sync_unpin(dma, domain, &unmapped_region_list);
828
829 if (do_accounting) {
830 vfio_lock_acct(dma, -unlocked, true);
831 return 0;
832 }
833 return unlocked;
834 }
835
836 static void vfio_remove_dma(struct vfio_iommu *iommu, struct vfio_dma *dma)
837 {
838 vfio_unmap_unpin(iommu, dma, true);
839 vfio_unlink_dma(iommu, dma);
840 put_task_struct(dma->task);
841 kfree(dma);
842 iommu->dma_avail++;
843 }
844
845 static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
846 {
847 struct vfio_domain *domain;
848 unsigned long bitmap = ULONG_MAX;
849
850 mutex_lock(&iommu->lock);
851 list_for_each_entry(domain, &iommu->domain_list, next)
852 bitmap &= domain->domain->pgsize_bitmap;
853 mutex_unlock(&iommu->lock);
854
855 /*
856 * In case the IOMMU supports page sizes smaller than PAGE_SIZE
857 * we pretend PAGE_SIZE is supported and hide sub-PAGE_SIZE sizes.
858 * That way the user will be able to map/unmap buffers whose size/
859 * start address is aligned with PAGE_SIZE. Pinning code uses that
860 * granularity while iommu driver can use the sub-PAGE_SIZE size
861 * to map the buffer.
862 */
863 if (bitmap & ~PAGE_MASK) {
864 bitmap &= PAGE_MASK;
865 bitmap |= PAGE_SIZE;
866 }
867
868 return bitmap;
869 }
870
871 static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
872 struct vfio_iommu_type1_dma_unmap *unmap)
873 {
874 uint64_t mask;
875 struct vfio_dma *dma, *dma_last = NULL;
876 size_t unmapped = 0;
877 int ret = 0, retries = 0;
878
879 mask = ((uint64_t)1 << __ffs(vfio_pgsize_bitmap(iommu))) - 1;
880
881 if (unmap->iova & mask)
882 return -EINVAL;
883 if (!unmap->size || unmap->size & mask)
884 return -EINVAL;
885 if (unmap->iova + unmap->size - 1 < unmap->iova ||
886 unmap->size > SIZE_MAX)
887 return -EINVAL;
888
889 WARN_ON(mask & PAGE_MASK);
890 again:
891 mutex_lock(&iommu->lock);
892
893 /*
894 * vfio-iommu-type1 (v1) - User mappings were coalesced together to
895 * avoid tracking individual mappings. This means that the granularity
896 * of the original mapping was lost and the user was allowed to attempt
897 * to unmap any range. Depending on the contiguousness of physical
898 * memory and page sizes supported by the IOMMU, arbitrary unmaps may
899 * or may not have worked. We only guaranteed unmap granularity
900 * matching the original mapping; even though it was untracked here,
901 * the original mappings are reflected in IOMMU mappings. This
902 * resulted in a couple unusual behaviors. First, if a range is not
903 * able to be unmapped, ex. a set of 4k pages that was mapped as a
904 * 2M hugepage into the IOMMU, the unmap ioctl returns success but with
905 * a zero sized unmap. Also, if an unmap request overlaps the first
906 * address of a hugepage, the IOMMU will unmap the entire hugepage.
907 * This also returns success and the returned unmap size reflects the
908 * actual size unmapped.
909 *
910 * We attempt to maintain compatibility with this "v1" interface, but
911 * we take control out of the hands of the IOMMU. Therefore, an unmap
912 * request offset from the beginning of the original mapping will
913 * return success with zero sized unmap. And an unmap request covering
914 * the first iova of mapping will unmap the entire range.
915 *
916 * The v2 version of this interface intends to be more deterministic.
917 * Unmap requests must fully cover previous mappings. Multiple
918 * mappings may still be unmaped by specifying large ranges, but there
919 * must not be any previous mappings bisected by the range. An error
920 * will be returned if these conditions are not met. The v2 interface
921 * will only return success and a size of zero if there were no
922 * mappings within the range.
923 */
924 if (iommu->v2) {
925 dma = vfio_find_dma(iommu, unmap->iova, 1);
926 if (dma && dma->iova != unmap->iova) {
927 ret = -EINVAL;
928 goto unlock;
929 }
930 dma = vfio_find_dma(iommu, unmap->iova + unmap->size - 1, 0);
931 if (dma && dma->iova + dma->size != unmap->iova + unmap->size) {
932 ret = -EINVAL;
933 goto unlock;
934 }
935 }
936
937 while ((dma = vfio_find_dma(iommu, unmap->iova, unmap->size))) {
938 if (!iommu->v2 && unmap->iova > dma->iova)
939 break;
940 /*
941 * Task with same address space who mapped this iova range is
942 * allowed to unmap the iova range.
943 */
944 if (dma->task->mm != current->mm)
945 break;
946
947 if (!RB_EMPTY_ROOT(&dma->pfn_list)) {
948 struct vfio_iommu_type1_dma_unmap nb_unmap;
949
950 if (dma_last == dma) {
951 BUG_ON(++retries > 10);
952 } else {
953 dma_last = dma;
954 retries = 0;
955 }
956
957 nb_unmap.iova = dma->iova;
958 nb_unmap.size = dma->size;
959
960 /*
961 * Notify anyone (mdev vendor drivers) to invalidate and
962 * unmap iovas within the range we're about to unmap.
963 * Vendor drivers MUST unpin pages in response to an
964 * invalidation.
965 */
966 mutex_unlock(&iommu->lock);
967 blocking_notifier_call_chain(&iommu->notifier,
968 VFIO_IOMMU_NOTIFY_DMA_UNMAP,
969 &nb_unmap);
970 goto again;
971 }
972 unmapped += dma->size;
973 vfio_remove_dma(iommu, dma);
974 }
975
976 unlock:
977 mutex_unlock(&iommu->lock);
978
979 /* Report how much was unmapped */
980 unmap->size = unmapped;
981
982 return ret;
983 }
984
985 static int vfio_iommu_map(struct vfio_iommu *iommu, dma_addr_t iova,
986 unsigned long pfn, long npage, int prot)
987 {
988 struct vfio_domain *d;
989 int ret;
990
991 list_for_each_entry(d, &iommu->domain_list, next) {
992 ret = iommu_map(d->domain, iova, (phys_addr_t)pfn << PAGE_SHIFT,
993 npage << PAGE_SHIFT, prot | d->prot);
994 if (ret)
995 goto unwind;
996
997 cond_resched();
998 }
999
1000 return 0;
1001
1002 unwind:
1003 list_for_each_entry_continue_reverse(d, &iommu->domain_list, next)
1004 iommu_unmap(d->domain, iova, npage << PAGE_SHIFT);
1005
1006 return ret;
1007 }
1008
1009 static int vfio_pin_map_dma(struct vfio_iommu *iommu, struct vfio_dma *dma,
1010 size_t map_size)
1011 {
1012 dma_addr_t iova = dma->iova;
1013 unsigned long vaddr = dma->vaddr;
1014 size_t size = map_size;
1015 long npage;
1016 unsigned long pfn, limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1017 int ret = 0;
1018
1019 while (size) {
1020 /* Pin a contiguous chunk of memory */
1021 npage = vfio_pin_pages_remote(dma, vaddr + dma->size,
1022 size >> PAGE_SHIFT, &pfn, limit);
1023 if (npage <= 0) {
1024 WARN_ON(!npage);
1025 ret = (int)npage;
1026 break;
1027 }
1028
1029 /* Map it! */
1030 ret = vfio_iommu_map(iommu, iova + dma->size, pfn, npage,
1031 dma->prot);
1032 if (ret) {
1033 vfio_unpin_pages_remote(dma, iova + dma->size, pfn,
1034 npage, true);
1035 break;
1036 }
1037
1038 size -= npage << PAGE_SHIFT;
1039 dma->size += npage << PAGE_SHIFT;
1040 }
1041
1042 dma->iommu_mapped = true;
1043
1044 if (ret)
1045 vfio_remove_dma(iommu, dma);
1046
1047 return ret;
1048 }
1049
1050 static int vfio_dma_do_map(struct vfio_iommu *iommu,
1051 struct vfio_iommu_type1_dma_map *map)
1052 {
1053 dma_addr_t iova = map->iova;
1054 unsigned long vaddr = map->vaddr;
1055 size_t size = map->size;
1056 int ret = 0, prot = 0;
1057 uint64_t mask;
1058 struct vfio_dma *dma;
1059
1060 /* Verify that none of our __u64 fields overflow */
1061 if (map->size != size || map->vaddr != vaddr || map->iova != iova)
1062 return -EINVAL;
1063
1064 mask = ((uint64_t)1 << __ffs(vfio_pgsize_bitmap(iommu))) - 1;
1065
1066 WARN_ON(mask & PAGE_MASK);
1067
1068 /* READ/WRITE from device perspective */
1069 if (map->flags & VFIO_DMA_MAP_FLAG_WRITE)
1070 prot |= IOMMU_WRITE;
1071 if (map->flags & VFIO_DMA_MAP_FLAG_READ)
1072 prot |= IOMMU_READ;
1073
1074 if (!prot || !size || (size | iova | vaddr) & mask)
1075 return -EINVAL;
1076
1077 /* Don't allow IOVA or virtual address wrap */
1078 if (iova + size - 1 < iova || vaddr + size - 1 < vaddr)
1079 return -EINVAL;
1080
1081 mutex_lock(&iommu->lock);
1082
1083 if (vfio_find_dma(iommu, iova, size)) {
1084 ret = -EEXIST;
1085 goto out_unlock;
1086 }
1087
1088 if (!iommu->dma_avail) {
1089 ret = -ENOSPC;
1090 goto out_unlock;
1091 }
1092
1093 dma = kzalloc(sizeof(*dma), GFP_KERNEL);
1094 if (!dma) {
1095 ret = -ENOMEM;
1096 goto out_unlock;
1097 }
1098
1099 iommu->dma_avail--;
1100 dma->iova = iova;
1101 dma->vaddr = vaddr;
1102 dma->prot = prot;
1103
1104 /*
1105 * We need to be able to both add to a task's locked memory and test
1106 * against the locked memory limit and we need to be able to do both
1107 * outside of this call path as pinning can be asynchronous via the
1108 * external interfaces for mdev devices. RLIMIT_MEMLOCK requires a
1109 * task_struct and VM locked pages requires an mm_struct, however
1110 * holding an indefinite mm reference is not recommended, therefore we
1111 * only hold a reference to a task. We could hold a reference to
1112 * current, however QEMU uses this call path through vCPU threads,
1113 * which can be killed resulting in a NULL mm and failure in the unmap
1114 * path when called via a different thread. Avoid this problem by
1115 * using the group_leader as threads within the same group require
1116 * both CLONE_THREAD and CLONE_VM and will therefore use the same
1117 * mm_struct.
1118 *
1119 * Previously we also used the task for testing CAP_IPC_LOCK at the
1120 * time of pinning and accounting, however has_capability() makes use
1121 * of real_cred, a copy-on-write field, so we can't guarantee that it
1122 * matches group_leader, or in fact that it might not change by the
1123 * time it's evaluated. If a process were to call MAP_DMA with
1124 * CAP_IPC_LOCK but later drop it, it doesn't make sense that they
1125 * possibly see different results for an iommu_mapped vfio_dma vs
1126 * externally mapped. Therefore track CAP_IPC_LOCK in vfio_dma at the
1127 * time of calling MAP_DMA.
1128 */
1129 get_task_struct(current->group_leader);
1130 dma->task = current->group_leader;
1131 dma->lock_cap = capable(CAP_IPC_LOCK);
1132
1133 dma->pfn_list = RB_ROOT;
1134
1135 /* Insert zero-sized and grow as we map chunks of it */
1136 vfio_link_dma(iommu, dma);
1137
1138 /* Don't pin and map if container doesn't contain IOMMU capable domain*/
1139 if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
1140 dma->size = size;
1141 else
1142 ret = vfio_pin_map_dma(iommu, dma, size);
1143
1144 out_unlock:
1145 mutex_unlock(&iommu->lock);
1146 return ret;
1147 }
1148
1149 static int vfio_bus_type(struct device *dev, void *data)
1150 {
1151 struct bus_type **bus = data;
1152
1153 if (*bus && *bus != dev->bus)
1154 return -EINVAL;
1155
1156 *bus = dev->bus;
1157
1158 return 0;
1159 }
1160
1161 static int vfio_iommu_replay(struct vfio_iommu *iommu,
1162 struct vfio_domain *domain)
1163 {
1164 struct vfio_domain *d;
1165 struct rb_node *n;
1166 unsigned long limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1167 int ret;
1168
1169 /* Arbitrarily pick the first domain in the list for lookups */
1170 d = list_first_entry(&iommu->domain_list, struct vfio_domain, next);
1171 n = rb_first(&iommu->dma_list);
1172
1173 for (; n; n = rb_next(n)) {
1174 struct vfio_dma *dma;
1175 dma_addr_t iova;
1176
1177 dma = rb_entry(n, struct vfio_dma, node);
1178 iova = dma->iova;
1179
1180 while (iova < dma->iova + dma->size) {
1181 phys_addr_t phys;
1182 size_t size;
1183
1184 if (dma->iommu_mapped) {
1185 phys_addr_t p;
1186 dma_addr_t i;
1187
1188 phys = iommu_iova_to_phys(d->domain, iova);
1189
1190 if (WARN_ON(!phys)) {
1191 iova += PAGE_SIZE;
1192 continue;
1193 }
1194
1195 size = PAGE_SIZE;
1196 p = phys + size;
1197 i = iova + size;
1198 while (i < dma->iova + dma->size &&
1199 p == iommu_iova_to_phys(d->domain, i)) {
1200 size += PAGE_SIZE;
1201 p += PAGE_SIZE;
1202 i += PAGE_SIZE;
1203 }
1204 } else {
1205 unsigned long pfn;
1206 unsigned long vaddr = dma->vaddr +
1207 (iova - dma->iova);
1208 size_t n = dma->iova + dma->size - iova;
1209 long npage;
1210
1211 npage = vfio_pin_pages_remote(dma, vaddr,
1212 n >> PAGE_SHIFT,
1213 &pfn, limit);
1214 if (npage <= 0) {
1215 WARN_ON(!npage);
1216 ret = (int)npage;
1217 return ret;
1218 }
1219
1220 phys = pfn << PAGE_SHIFT;
1221 size = npage << PAGE_SHIFT;
1222 }
1223
1224 ret = iommu_map(domain->domain, iova, phys,
1225 size, dma->prot | domain->prot);
1226 if (ret)
1227 return ret;
1228
1229 iova += size;
1230 }
1231 dma->iommu_mapped = true;
1232 }
1233 return 0;
1234 }
1235
1236 /*
1237 * We change our unmap behavior slightly depending on whether the IOMMU
1238 * supports fine-grained superpages. IOMMUs like AMD-Vi will use a superpage
1239 * for practically any contiguous power-of-two mapping we give it. This means
1240 * we don't need to look for contiguous chunks ourselves to make unmapping
1241 * more efficient. On IOMMUs with coarse-grained super pages, like Intel VT-d
1242 * with discrete 2M/1G/512G/1T superpages, identifying contiguous chunks
1243 * significantly boosts non-hugetlbfs mappings and doesn't seem to hurt when
1244 * hugetlbfs is in use.
1245 */
1246 static void vfio_test_domain_fgsp(struct vfio_domain *domain)
1247 {
1248 struct page *pages;
1249 int ret, order = get_order(PAGE_SIZE * 2);
1250
1251 pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, order);
1252 if (!pages)
1253 return;
1254
1255 ret = iommu_map(domain->domain, 0, page_to_phys(pages), PAGE_SIZE * 2,
1256 IOMMU_READ | IOMMU_WRITE | domain->prot);
1257 if (!ret) {
1258 size_t unmapped = iommu_unmap(domain->domain, 0, PAGE_SIZE);
1259
1260 if (unmapped == PAGE_SIZE)
1261 iommu_unmap(domain->domain, PAGE_SIZE, PAGE_SIZE);
1262 else
1263 domain->fgsp = true;
1264 }
1265
1266 __free_pages(pages, order);
1267 }
1268
1269 static struct vfio_group *find_iommu_group(struct vfio_domain *domain,
1270 struct iommu_group *iommu_group)
1271 {
1272 struct vfio_group *g;
1273
1274 list_for_each_entry(g, &domain->group_list, next) {
1275 if (g->iommu_group == iommu_group)
1276 return g;
1277 }
1278
1279 return NULL;
1280 }
1281
1282 static bool vfio_iommu_has_sw_msi(struct iommu_group *group, phys_addr_t *base)
1283 {
1284 struct list_head group_resv_regions;
1285 struct iommu_resv_region *region, *next;
1286 bool ret = false;
1287
1288 INIT_LIST_HEAD(&group_resv_regions);
1289 iommu_get_group_resv_regions(group, &group_resv_regions);
1290 list_for_each_entry(region, &group_resv_regions, list) {
1291 /*
1292 * The presence of any 'real' MSI regions should take
1293 * precedence over the software-managed one if the
1294 * IOMMU driver happens to advertise both types.
1295 */
1296 if (region->type == IOMMU_RESV_MSI) {
1297 ret = false;
1298 break;
1299 }
1300
1301 if (region->type == IOMMU_RESV_SW_MSI) {
1302 *base = region->start;
1303 ret = true;
1304 }
1305 }
1306 list_for_each_entry_safe(region, next, &group_resv_regions, list)
1307 kfree(region);
1308 return ret;
1309 }
1310
1311 static struct device *vfio_mdev_get_iommu_device(struct device *dev)
1312 {
1313 struct device *(*fn)(struct device *dev);
1314 struct device *iommu_device;
1315
1316 fn = symbol_get(mdev_get_iommu_device);
1317 if (fn) {
1318 iommu_device = fn(dev);
1319 symbol_put(mdev_get_iommu_device);
1320
1321 return iommu_device;
1322 }
1323
1324 return NULL;
1325 }
1326
1327 static int vfio_mdev_attach_domain(struct device *dev, void *data)
1328 {
1329 struct iommu_domain *domain = data;
1330 struct device *iommu_device;
1331
1332 iommu_device = vfio_mdev_get_iommu_device(dev);
1333 if (iommu_device) {
1334 if (iommu_dev_feature_enabled(iommu_device, IOMMU_DEV_FEAT_AUX))
1335 return iommu_aux_attach_device(domain, iommu_device);
1336 else
1337 return iommu_attach_device(domain, iommu_device);
1338 }
1339
1340 return -EINVAL;
1341 }
1342
1343 static int vfio_mdev_detach_domain(struct device *dev, void *data)
1344 {
1345 struct iommu_domain *domain = data;
1346 struct device *iommu_device;
1347
1348 iommu_device = vfio_mdev_get_iommu_device(dev);
1349 if (iommu_device) {
1350 if (iommu_dev_feature_enabled(iommu_device, IOMMU_DEV_FEAT_AUX))
1351 iommu_aux_detach_device(domain, iommu_device);
1352 else
1353 iommu_detach_device(domain, iommu_device);
1354 }
1355
1356 return 0;
1357 }
1358
1359 static int vfio_iommu_attach_group(struct vfio_domain *domain,
1360 struct vfio_group *group)
1361 {
1362 if (group->mdev_group)
1363 return iommu_group_for_each_dev(group->iommu_group,
1364 domain->domain,
1365 vfio_mdev_attach_domain);
1366 else
1367 return iommu_attach_group(domain->domain, group->iommu_group);
1368 }
1369
1370 static void vfio_iommu_detach_group(struct vfio_domain *domain,
1371 struct vfio_group *group)
1372 {
1373 if (group->mdev_group)
1374 iommu_group_for_each_dev(group->iommu_group, domain->domain,
1375 vfio_mdev_detach_domain);
1376 else
1377 iommu_detach_group(domain->domain, group->iommu_group);
1378 }
1379
1380 static bool vfio_bus_is_mdev(struct bus_type *bus)
1381 {
1382 struct bus_type *mdev_bus;
1383 bool ret = false;
1384
1385 mdev_bus = symbol_get(mdev_bus_type);
1386 if (mdev_bus) {
1387 ret = (bus == mdev_bus);
1388 symbol_put(mdev_bus_type);
1389 }
1390
1391 return ret;
1392 }
1393
1394 static int vfio_mdev_iommu_device(struct device *dev, void *data)
1395 {
1396 struct device **old = data, *new;
1397
1398 new = vfio_mdev_get_iommu_device(dev);
1399 if (!new || (*old && *old != new))
1400 return -EINVAL;
1401
1402 *old = new;
1403
1404 return 0;
1405 }
1406
1407 static int vfio_iommu_type1_attach_group(void *iommu_data,
1408 struct iommu_group *iommu_group)
1409 {
1410 struct vfio_iommu *iommu = iommu_data;
1411 struct vfio_group *group;
1412 struct vfio_domain *domain, *d;
1413 struct bus_type *bus = NULL;
1414 int ret;
1415 bool resv_msi, msi_remap;
1416 phys_addr_t resv_msi_base;
1417
1418 mutex_lock(&iommu->lock);
1419
1420 list_for_each_entry(d, &iommu->domain_list, next) {
1421 if (find_iommu_group(d, iommu_group)) {
1422 mutex_unlock(&iommu->lock);
1423 return -EINVAL;
1424 }
1425 }
1426
1427 if (iommu->external_domain) {
1428 if (find_iommu_group(iommu->external_domain, iommu_group)) {
1429 mutex_unlock(&iommu->lock);
1430 return -EINVAL;
1431 }
1432 }
1433
1434 group = kzalloc(sizeof(*group), GFP_KERNEL);
1435 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
1436 if (!group || !domain) {
1437 ret = -ENOMEM;
1438 goto out_free;
1439 }
1440
1441 group->iommu_group = iommu_group;
1442
1443 /* Determine bus_type in order to allocate a domain */
1444 ret = iommu_group_for_each_dev(iommu_group, &bus, vfio_bus_type);
1445 if (ret)
1446 goto out_free;
1447
1448 if (vfio_bus_is_mdev(bus)) {
1449 struct device *iommu_device = NULL;
1450
1451 group->mdev_group = true;
1452
1453 /* Determine the isolation type */
1454 ret = iommu_group_for_each_dev(iommu_group, &iommu_device,
1455 vfio_mdev_iommu_device);
1456 if (ret || !iommu_device) {
1457 if (!iommu->external_domain) {
1458 INIT_LIST_HEAD(&domain->group_list);
1459 iommu->external_domain = domain;
1460 } else {
1461 kfree(domain);
1462 }
1463
1464 list_add(&group->next,
1465 &iommu->external_domain->group_list);
1466 mutex_unlock(&iommu->lock);
1467
1468 return 0;
1469 }
1470
1471 bus = iommu_device->bus;
1472 }
1473
1474 domain->domain = iommu_domain_alloc(bus);
1475 if (!domain->domain) {
1476 ret = -EIO;
1477 goto out_free;
1478 }
1479
1480 if (iommu->nesting) {
1481 int attr = 1;
1482
1483 ret = iommu_domain_set_attr(domain->domain, DOMAIN_ATTR_NESTING,
1484 &attr);
1485 if (ret)
1486 goto out_domain;
1487 }
1488
1489 ret = vfio_iommu_attach_group(domain, group);
1490 if (ret)
1491 goto out_domain;
1492
1493 resv_msi = vfio_iommu_has_sw_msi(iommu_group, &resv_msi_base);
1494
1495 INIT_LIST_HEAD(&domain->group_list);
1496 list_add(&group->next, &domain->group_list);
1497
1498 msi_remap = irq_domain_check_msi_remap() ||
1499 iommu_capable(bus, IOMMU_CAP_INTR_REMAP);
1500
1501 if (!allow_unsafe_interrupts && !msi_remap) {
1502 pr_warn("%s: No interrupt remapping support. Use the module param \"allow_unsafe_interrupts\" to enable VFIO IOMMU support on this platform\n",
1503 __func__);
1504 ret = -EPERM;
1505 goto out_detach;
1506 }
1507
1508 if (iommu_capable(bus, IOMMU_CAP_CACHE_COHERENCY))
1509 domain->prot |= IOMMU_CACHE;
1510
1511 /*
1512 * Try to match an existing compatible domain. We don't want to
1513 * preclude an IOMMU driver supporting multiple bus_types and being
1514 * able to include different bus_types in the same IOMMU domain, so
1515 * we test whether the domains use the same iommu_ops rather than
1516 * testing if they're on the same bus_type.
1517 */
1518 list_for_each_entry(d, &iommu->domain_list, next) {
1519 if (d->domain->ops == domain->domain->ops &&
1520 d->prot == domain->prot) {
1521 vfio_iommu_detach_group(domain, group);
1522 if (!vfio_iommu_attach_group(d, group)) {
1523 list_add(&group->next, &d->group_list);
1524 iommu_domain_free(domain->domain);
1525 kfree(domain);
1526 mutex_unlock(&iommu->lock);
1527 return 0;
1528 }
1529
1530 ret = vfio_iommu_attach_group(domain, group);
1531 if (ret)
1532 goto out_domain;
1533 }
1534 }
1535
1536 vfio_test_domain_fgsp(domain);
1537
1538 /* replay mappings on new domains */
1539 ret = vfio_iommu_replay(iommu, domain);
1540 if (ret)
1541 goto out_detach;
1542
1543 if (resv_msi) {
1544 ret = iommu_get_msi_cookie(domain->domain, resv_msi_base);
1545 if (ret)
1546 goto out_detach;
1547 }
1548
1549 list_add(&domain->next, &iommu->domain_list);
1550
1551 mutex_unlock(&iommu->lock);
1552
1553 return 0;
1554
1555 out_detach:
1556 vfio_iommu_detach_group(domain, group);
1557 out_domain:
1558 iommu_domain_free(domain->domain);
1559 out_free:
1560 kfree(domain);
1561 kfree(group);
1562 mutex_unlock(&iommu->lock);
1563 return ret;
1564 }
1565
1566 static void vfio_iommu_unmap_unpin_all(struct vfio_iommu *iommu)
1567 {
1568 struct rb_node *node;
1569
1570 while ((node = rb_first(&iommu->dma_list)))
1571 vfio_remove_dma(iommu, rb_entry(node, struct vfio_dma, node));
1572 }
1573
1574 static void vfio_iommu_unmap_unpin_reaccount(struct vfio_iommu *iommu)
1575 {
1576 struct rb_node *n, *p;
1577
1578 n = rb_first(&iommu->dma_list);
1579 for (; n; n = rb_next(n)) {
1580 struct vfio_dma *dma;
1581 long locked = 0, unlocked = 0;
1582
1583 dma = rb_entry(n, struct vfio_dma, node);
1584 unlocked += vfio_unmap_unpin(iommu, dma, false);
1585 p = rb_first(&dma->pfn_list);
1586 for (; p; p = rb_next(p)) {
1587 struct vfio_pfn *vpfn = rb_entry(p, struct vfio_pfn,
1588 node);
1589
1590 if (!is_invalid_reserved_pfn(vpfn->pfn))
1591 locked++;
1592 }
1593 vfio_lock_acct(dma, locked - unlocked, true);
1594 }
1595 }
1596
1597 static void vfio_sanity_check_pfn_list(struct vfio_iommu *iommu)
1598 {
1599 struct rb_node *n;
1600
1601 n = rb_first(&iommu->dma_list);
1602 for (; n; n = rb_next(n)) {
1603 struct vfio_dma *dma;
1604
1605 dma = rb_entry(n, struct vfio_dma, node);
1606
1607 if (WARN_ON(!RB_EMPTY_ROOT(&dma->pfn_list)))
1608 break;
1609 }
1610 /* mdev vendor driver must unregister notifier */
1611 WARN_ON(iommu->notifier.head);
1612 }
1613
1614 static void vfio_iommu_type1_detach_group(void *iommu_data,
1615 struct iommu_group *iommu_group)
1616 {
1617 struct vfio_iommu *iommu = iommu_data;
1618 struct vfio_domain *domain;
1619 struct vfio_group *group;
1620
1621 mutex_lock(&iommu->lock);
1622
1623 if (iommu->external_domain) {
1624 group = find_iommu_group(iommu->external_domain, iommu_group);
1625 if (group) {
1626 list_del(&group->next);
1627 kfree(group);
1628
1629 if (list_empty(&iommu->external_domain->group_list)) {
1630 vfio_sanity_check_pfn_list(iommu);
1631
1632 if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
1633 vfio_iommu_unmap_unpin_all(iommu);
1634
1635 kfree(iommu->external_domain);
1636 iommu->external_domain = NULL;
1637 }
1638 goto detach_group_done;
1639 }
1640 }
1641
1642 list_for_each_entry(domain, &iommu->domain_list, next) {
1643 group = find_iommu_group(domain, iommu_group);
1644 if (!group)
1645 continue;
1646
1647 vfio_iommu_detach_group(domain, group);
1648 list_del(&group->next);
1649 kfree(group);
1650 /*
1651 * Group ownership provides privilege, if the group list is
1652 * empty, the domain goes away. If it's the last domain with
1653 * iommu and external domain doesn't exist, then all the
1654 * mappings go away too. If it's the last domain with iommu and
1655 * external domain exist, update accounting
1656 */
1657 if (list_empty(&domain->group_list)) {
1658 if (list_is_singular(&iommu->domain_list)) {
1659 if (!iommu->external_domain)
1660 vfio_iommu_unmap_unpin_all(iommu);
1661 else
1662 vfio_iommu_unmap_unpin_reaccount(iommu);
1663 }
1664 iommu_domain_free(domain->domain);
1665 list_del(&domain->next);
1666 kfree(domain);
1667 }
1668 break;
1669 }
1670
1671 detach_group_done:
1672 mutex_unlock(&iommu->lock);
1673 }
1674
1675 static void *vfio_iommu_type1_open(unsigned long arg)
1676 {
1677 struct vfio_iommu *iommu;
1678
1679 iommu = kzalloc(sizeof(*iommu), GFP_KERNEL);
1680 if (!iommu)
1681 return ERR_PTR(-ENOMEM);
1682
1683 switch (arg) {
1684 case VFIO_TYPE1_IOMMU:
1685 break;
1686 case VFIO_TYPE1_NESTING_IOMMU:
1687 iommu->nesting = true;
1688 /* fall through */
1689 case VFIO_TYPE1v2_IOMMU:
1690 iommu->v2 = true;
1691 break;
1692 default:
1693 kfree(iommu);
1694 return ERR_PTR(-EINVAL);
1695 }
1696
1697 INIT_LIST_HEAD(&iommu->domain_list);
1698 iommu->dma_list = RB_ROOT;
1699 iommu->dma_avail = dma_entry_limit;
1700 mutex_init(&iommu->lock);
1701 BLOCKING_INIT_NOTIFIER_HEAD(&iommu->notifier);
1702
1703 return iommu;
1704 }
1705
1706 static void vfio_release_domain(struct vfio_domain *domain, bool external)
1707 {
1708 struct vfio_group *group, *group_tmp;
1709
1710 list_for_each_entry_safe(group, group_tmp,
1711 &domain->group_list, next) {
1712 if (!external)
1713 vfio_iommu_detach_group(domain, group);
1714 list_del(&group->next);
1715 kfree(group);
1716 }
1717
1718 if (!external)
1719 iommu_domain_free(domain->domain);
1720 }
1721
1722 static void vfio_iommu_type1_release(void *iommu_data)
1723 {
1724 struct vfio_iommu *iommu = iommu_data;
1725 struct vfio_domain *domain, *domain_tmp;
1726
1727 if (iommu->external_domain) {
1728 vfio_release_domain(iommu->external_domain, true);
1729 vfio_sanity_check_pfn_list(iommu);
1730 kfree(iommu->external_domain);
1731 }
1732
1733 vfio_iommu_unmap_unpin_all(iommu);
1734
1735 list_for_each_entry_safe(domain, domain_tmp,
1736 &iommu->domain_list, next) {
1737 vfio_release_domain(domain, false);
1738 list_del(&domain->next);
1739 kfree(domain);
1740 }
1741 kfree(iommu);
1742 }
1743
1744 static int vfio_domains_have_iommu_cache(struct vfio_iommu *iommu)
1745 {
1746 struct vfio_domain *domain;
1747 int ret = 1;
1748
1749 mutex_lock(&iommu->lock);
1750 list_for_each_entry(domain, &iommu->domain_list, next) {
1751 if (!(domain->prot & IOMMU_CACHE)) {
1752 ret = 0;
1753 break;
1754 }
1755 }
1756 mutex_unlock(&iommu->lock);
1757
1758 return ret;
1759 }
1760
1761 static long vfio_iommu_type1_ioctl(void *iommu_data,
1762 unsigned int cmd, unsigned long arg)
1763 {
1764 struct vfio_iommu *iommu = iommu_data;
1765 unsigned long minsz;
1766
1767 if (cmd == VFIO_CHECK_EXTENSION) {
1768 switch (arg) {
1769 case VFIO_TYPE1_IOMMU:
1770 case VFIO_TYPE1v2_IOMMU:
1771 case VFIO_TYPE1_NESTING_IOMMU:
1772 return 1;
1773 case VFIO_DMA_CC_IOMMU:
1774 if (!iommu)
1775 return 0;
1776 return vfio_domains_have_iommu_cache(iommu);
1777 default:
1778 return 0;
1779 }
1780 } else if (cmd == VFIO_IOMMU_GET_INFO) {
1781 struct vfio_iommu_type1_info info;
1782
1783 minsz = offsetofend(struct vfio_iommu_type1_info, iova_pgsizes);
1784
1785 if (copy_from_user(&info, (void __user *)arg, minsz))
1786 return -EFAULT;
1787
1788 if (info.argsz < minsz)
1789 return -EINVAL;
1790
1791 info.flags = VFIO_IOMMU_INFO_PGSIZES;
1792
1793 info.iova_pgsizes = vfio_pgsize_bitmap(iommu);
1794
1795 return copy_to_user((void __user *)arg, &info, minsz) ?
1796 -EFAULT : 0;
1797
1798 } else if (cmd == VFIO_IOMMU_MAP_DMA) {
1799 struct vfio_iommu_type1_dma_map map;
1800 uint32_t mask = VFIO_DMA_MAP_FLAG_READ |
1801 VFIO_DMA_MAP_FLAG_WRITE;
1802
1803 minsz = offsetofend(struct vfio_iommu_type1_dma_map, size);
1804
1805 if (copy_from_user(&map, (void __user *)arg, minsz))
1806 return -EFAULT;
1807
1808 if (map.argsz < minsz || map.flags & ~mask)
1809 return -EINVAL;
1810
1811 return vfio_dma_do_map(iommu, &map);
1812
1813 } else if (cmd == VFIO_IOMMU_UNMAP_DMA) {
1814 struct vfio_iommu_type1_dma_unmap unmap;
1815 long ret;
1816
1817 minsz = offsetofend(struct vfio_iommu_type1_dma_unmap, size);
1818
1819 if (copy_from_user(&unmap, (void __user *)arg, minsz))
1820 return -EFAULT;
1821
1822 if (unmap.argsz < minsz || unmap.flags)
1823 return -EINVAL;
1824
1825 ret = vfio_dma_do_unmap(iommu, &unmap);
1826 if (ret)
1827 return ret;
1828
1829 return copy_to_user((void __user *)arg, &unmap, minsz) ?
1830 -EFAULT : 0;
1831 }
1832
1833 return -ENOTTY;
1834 }
1835
1836 static int vfio_iommu_type1_register_notifier(void *iommu_data,
1837 unsigned long *events,
1838 struct notifier_block *nb)
1839 {
1840 struct vfio_iommu *iommu = iommu_data;
1841
1842 /* clear known events */
1843 *events &= ~VFIO_IOMMU_NOTIFY_DMA_UNMAP;
1844
1845 /* refuse to register if still events remaining */
1846 if (*events)
1847 return -EINVAL;
1848
1849 return blocking_notifier_chain_register(&iommu->notifier, nb);
1850 }
1851
1852 static int vfio_iommu_type1_unregister_notifier(void *iommu_data,
1853 struct notifier_block *nb)
1854 {
1855 struct vfio_iommu *iommu = iommu_data;
1856
1857 return blocking_notifier_chain_unregister(&iommu->notifier, nb);
1858 }
1859
1860 static const struct vfio_iommu_driver_ops vfio_iommu_driver_ops_type1 = {
1861 .name = "vfio-iommu-type1",
1862 .owner = THIS_MODULE,
1863 .open = vfio_iommu_type1_open,
1864 .release = vfio_iommu_type1_release,
1865 .ioctl = vfio_iommu_type1_ioctl,
1866 .attach_group = vfio_iommu_type1_attach_group,
1867 .detach_group = vfio_iommu_type1_detach_group,
1868 .pin_pages = vfio_iommu_type1_pin_pages,
1869 .unpin_pages = vfio_iommu_type1_unpin_pages,
1870 .register_notifier = vfio_iommu_type1_register_notifier,
1871 .unregister_notifier = vfio_iommu_type1_unregister_notifier,
1872 };
1873
1874 static int __init vfio_iommu_type1_init(void)
1875 {
1876 return vfio_register_iommu_driver(&vfio_iommu_driver_ops_type1);
1877 }
1878
1879 static void __exit vfio_iommu_type1_cleanup(void)
1880 {
1881 vfio_unregister_iommu_driver(&vfio_iommu_driver_ops_type1);
1882 }
1883
1884 module_init(vfio_iommu_type1_init);
1885 module_exit(vfio_iommu_type1_cleanup);
1886
1887 MODULE_VERSION(DRIVER_VERSION);
1888 MODULE_LICENSE("GPL v2");
1889 MODULE_AUTHOR(DRIVER_AUTHOR);
1890 MODULE_DESCRIPTION(DRIVER_DESC);