1 // SPDX-License-Identifier: GPL-2.0-only
3 * VFIO: IOMMU DMA mapping support for Type1 IOMMU
5 * Copyright (C) 2012 Red Hat, Inc. All rights reserved.
6 * Author: Alex Williamson <alex.williamson@redhat.com>
8 * Derived from original vfio:
9 * Copyright 2010 Cisco Systems, Inc. All rights reserved.
10 * Author: Tom Lyon, pugs@cisco.com
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 * userpsace 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.
24 #include <linux/compat.h>
25 #include <linux/device.h>
27 #include <linux/iommu.h>
28 #include <linux/module.h>
30 #include <linux/rbtree.h>
31 #include <linux/sched/signal.h>
32 #include <linux/sched/mm.h>
33 #include <linux/slab.h>
34 #include <linux/uaccess.h>
35 #include <linux/vfio.h>
36 #include <linux/workqueue.h>
37 #include <linux/mdev.h>
38 #include <linux/notifier.h>
39 #include <linux/dma-iommu.h>
40 #include <linux/irqdomain.h>
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"
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.");
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.");
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).");
64 struct list_head domain_list;
65 struct list_head iova_list;
66 struct vfio_domain *external_domain; /* domain for external user */
68 struct rb_root dma_list;
69 struct blocking_notifier_head notifier;
70 unsigned int dma_avail;
76 struct iommu_domain *domain;
77 struct list_head next;
78 struct list_head group_list;
79 int prot; /* IOMMU_CACHE */
80 bool fgsp; /* Fine-grained super pages */
85 dma_addr_t iova; /* Device address */
86 unsigned long vaddr; /* Process virtual addr */
87 size_t size; /* Map size (bytes) */
88 int prot; /* IOMMU_READ/WRITE */
90 bool lock_cap; /* capable(CAP_IPC_LOCK) */
91 struct task_struct *task;
92 struct rb_root pfn_list; /* Ex-user pinned pfn list */
96 struct iommu_group *iommu_group;
97 struct list_head next;
98 bool mdev_group; /* An mdev group */
102 struct list_head list;
108 * Guest RAM pinning working set or DMA target
112 dma_addr_t iova; /* Device address */
113 unsigned long pfn; /* Host pfn */
117 struct vfio_regions {
118 struct list_head list;
124 #define IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu) \
125 (!list_empty(&iommu->domain_list))
127 static int put_pfn(unsigned long pfn, int prot);
130 * This code handles mapping and unmapping of user data buffers
131 * into DMA'ble space using the IOMMU
134 static struct vfio_dma *vfio_find_dma(struct vfio_iommu *iommu,
135 dma_addr_t start, size_t size)
137 struct rb_node *node = iommu->dma_list.rb_node;
140 struct vfio_dma *dma = rb_entry(node, struct vfio_dma, node);
142 if (start + size <= dma->iova)
143 node = node->rb_left;
144 else if (start >= dma->iova + dma->size)
145 node = node->rb_right;
153 static void vfio_link_dma(struct vfio_iommu *iommu, struct vfio_dma *new)
155 struct rb_node **link = &iommu->dma_list.rb_node, *parent = NULL;
156 struct vfio_dma *dma;
160 dma = rb_entry(parent, struct vfio_dma, node);
162 if (new->iova + new->size <= dma->iova)
163 link = &(*link)->rb_left;
165 link = &(*link)->rb_right;
168 rb_link_node(&new->node, parent, link);
169 rb_insert_color(&new->node, &iommu->dma_list);
172 static void vfio_unlink_dma(struct vfio_iommu *iommu, struct vfio_dma *old)
174 rb_erase(&old->node, &iommu->dma_list);
178 * Helper Functions for host iova-pfn list
180 static struct vfio_pfn *vfio_find_vpfn(struct vfio_dma *dma, dma_addr_t iova)
182 struct vfio_pfn *vpfn;
183 struct rb_node *node = dma->pfn_list.rb_node;
186 vpfn = rb_entry(node, struct vfio_pfn, node);
188 if (iova < vpfn->iova)
189 node = node->rb_left;
190 else if (iova > vpfn->iova)
191 node = node->rb_right;
198 static void vfio_link_pfn(struct vfio_dma *dma,
199 struct vfio_pfn *new)
201 struct rb_node **link, *parent = NULL;
202 struct vfio_pfn *vpfn;
204 link = &dma->pfn_list.rb_node;
207 vpfn = rb_entry(parent, struct vfio_pfn, node);
209 if (new->iova < vpfn->iova)
210 link = &(*link)->rb_left;
212 link = &(*link)->rb_right;
215 rb_link_node(&new->node, parent, link);
216 rb_insert_color(&new->node, &dma->pfn_list);
219 static void vfio_unlink_pfn(struct vfio_dma *dma, struct vfio_pfn *old)
221 rb_erase(&old->node, &dma->pfn_list);
224 static int vfio_add_to_pfn_list(struct vfio_dma *dma, dma_addr_t iova,
227 struct vfio_pfn *vpfn;
229 vpfn = kzalloc(sizeof(*vpfn), GFP_KERNEL);
235 atomic_set(&vpfn->ref_count, 1);
236 vfio_link_pfn(dma, vpfn);
240 static void vfio_remove_from_pfn_list(struct vfio_dma *dma,
241 struct vfio_pfn *vpfn)
243 vfio_unlink_pfn(dma, vpfn);
247 static struct vfio_pfn *vfio_iova_get_vfio_pfn(struct vfio_dma *dma,
250 struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
253 atomic_inc(&vpfn->ref_count);
257 static int vfio_iova_put_vfio_pfn(struct vfio_dma *dma, struct vfio_pfn *vpfn)
261 if (atomic_dec_and_test(&vpfn->ref_count)) {
262 ret = put_pfn(vpfn->pfn, dma->prot);
263 vfio_remove_from_pfn_list(dma, vpfn);
268 static int vfio_lock_acct(struct vfio_dma *dma, long npage, bool async)
270 struct mm_struct *mm;
276 mm = async ? get_task_mm(dma->task) : dma->task->mm;
278 return -ESRCH; /* process exited */
280 ret = down_write_killable(&mm->mmap_sem);
282 ret = __account_locked_vm(mm, abs(npage), npage > 0, dma->task,
284 up_write(&mm->mmap_sem);
294 * Some mappings aren't backed by a struct page, for example an mmap'd
295 * MMIO range for our own or another device. These use a different
296 * pfn conversion and shouldn't be tracked as locked pages.
298 static bool is_invalid_reserved_pfn(unsigned long pfn)
300 if (pfn_valid(pfn)) {
302 struct page *tail = pfn_to_page(pfn);
303 struct page *head = compound_head(tail);
304 reserved = !!(PageReserved(head));
307 * "head" is not a dangling pointer
308 * (compound_head takes care of that)
309 * but the hugepage may have been split
310 * from under us (and we may not hold a
311 * reference count on the head page so it can
312 * be reused before we run PageReferenced), so
313 * we've to check PageTail before returning
320 return PageReserved(tail);
326 static int put_pfn(unsigned long pfn, int prot)
328 if (!is_invalid_reserved_pfn(pfn)) {
329 struct page *page = pfn_to_page(pfn);
330 if (prot & IOMMU_WRITE)
338 static int vaddr_get_pfn(struct mm_struct *mm, unsigned long vaddr,
339 int prot, unsigned long *pfn)
341 struct page *page[1];
342 struct vm_area_struct *vma;
343 struct vm_area_struct *vmas[1];
344 unsigned int flags = 0;
347 if (prot & IOMMU_WRITE)
350 down_read(&mm->mmap_sem);
351 if (mm == current->mm) {
352 ret = get_user_pages(vaddr, 1, flags | FOLL_LONGTERM, page,
355 ret = get_user_pages_remote(NULL, mm, vaddr, 1, flags, page,
358 * The lifetime of a vaddr_get_pfn() page pin is
359 * userspace-controlled. In the fs-dax case this could
360 * lead to indefinite stalls in filesystem operations.
361 * Disallow attempts to pin fs-dax pages via this
364 if (ret > 0 && vma_is_fsdax(vmas[0])) {
369 up_read(&mm->mmap_sem);
372 *pfn = page_to_pfn(page[0]);
376 down_read(&mm->mmap_sem);
378 vma = find_vma_intersection(mm, vaddr, vaddr + 1);
380 if (vma && vma->vm_flags & VM_PFNMAP) {
381 *pfn = ((vaddr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
382 if (is_invalid_reserved_pfn(*pfn))
386 up_read(&mm->mmap_sem);
391 * Attempt to pin pages. We really don't want to track all the pfns and
392 * the iommu can only map chunks of consecutive pfns anyway, so get the
393 * first page and all consecutive pages with the same locking.
395 static long vfio_pin_pages_remote(struct vfio_dma *dma, unsigned long vaddr,
396 long npage, unsigned long *pfn_base,
399 unsigned long pfn = 0;
400 long ret, pinned = 0, lock_acct = 0;
402 dma_addr_t iova = vaddr - dma->vaddr + dma->iova;
404 /* This code path is only user initiated */
408 ret = vaddr_get_pfn(current->mm, vaddr, dma->prot, pfn_base);
413 rsvd = is_invalid_reserved_pfn(*pfn_base);
416 * Reserved pages aren't counted against the user, externally pinned
417 * pages are already counted against the user.
419 if (!rsvd && !vfio_find_vpfn(dma, iova)) {
420 if (!dma->lock_cap && current->mm->locked_vm + 1 > limit) {
421 put_pfn(*pfn_base, dma->prot);
422 pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n", __func__,
423 limit << PAGE_SHIFT);
429 if (unlikely(disable_hugepages))
432 /* Lock all the consecutive pages from pfn_base */
433 for (vaddr += PAGE_SIZE, iova += PAGE_SIZE; pinned < npage;
434 pinned++, vaddr += PAGE_SIZE, iova += PAGE_SIZE) {
435 ret = vaddr_get_pfn(current->mm, vaddr, dma->prot, &pfn);
439 if (pfn != *pfn_base + pinned ||
440 rsvd != is_invalid_reserved_pfn(pfn)) {
441 put_pfn(pfn, dma->prot);
445 if (!rsvd && !vfio_find_vpfn(dma, iova)) {
446 if (!dma->lock_cap &&
447 current->mm->locked_vm + lock_acct + 1 > limit) {
448 put_pfn(pfn, dma->prot);
449 pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n",
450 __func__, limit << PAGE_SHIFT);
459 ret = vfio_lock_acct(dma, lock_acct, false);
464 for (pfn = *pfn_base ; pinned ; pfn++, pinned--)
465 put_pfn(pfn, dma->prot);
474 static long vfio_unpin_pages_remote(struct vfio_dma *dma, dma_addr_t iova,
475 unsigned long pfn, long npage,
478 long unlocked = 0, locked = 0;
481 for (i = 0; i < npage; i++, iova += PAGE_SIZE) {
482 if (put_pfn(pfn++, dma->prot)) {
484 if (vfio_find_vpfn(dma, iova))
490 vfio_lock_acct(dma, locked - unlocked, true);
495 static int vfio_pin_page_external(struct vfio_dma *dma, unsigned long vaddr,
496 unsigned long *pfn_base, bool do_accounting)
498 struct mm_struct *mm;
501 mm = get_task_mm(dma->task);
505 ret = vaddr_get_pfn(mm, vaddr, dma->prot, pfn_base);
506 if (!ret && do_accounting && !is_invalid_reserved_pfn(*pfn_base)) {
507 ret = vfio_lock_acct(dma, 1, true);
509 put_pfn(*pfn_base, dma->prot);
511 pr_warn("%s: Task %s (%d) RLIMIT_MEMLOCK "
512 "(%ld) exceeded\n", __func__,
513 dma->task->comm, task_pid_nr(dma->task),
514 task_rlimit(dma->task, RLIMIT_MEMLOCK));
522 static int vfio_unpin_page_external(struct vfio_dma *dma, dma_addr_t iova,
526 struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
531 unlocked = vfio_iova_put_vfio_pfn(dma, vpfn);
534 vfio_lock_acct(dma, -unlocked, true);
539 static int vfio_iommu_type1_pin_pages(void *iommu_data,
540 unsigned long *user_pfn,
542 unsigned long *phys_pfn)
544 struct vfio_iommu *iommu = iommu_data;
546 unsigned long remote_vaddr;
547 struct vfio_dma *dma;
550 if (!iommu || !user_pfn || !phys_pfn)
553 /* Supported for v2 version only */
557 mutex_lock(&iommu->lock);
559 /* Fail if notifier list is empty */
560 if (!iommu->notifier.head) {
566 * If iommu capable domain exist in the container then all pages are
567 * already pinned and accounted. Accouting should be done if there is no
568 * iommu capable domain in the container.
570 do_accounting = !IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu);
572 for (i = 0; i < npage; i++) {
574 struct vfio_pfn *vpfn;
576 iova = user_pfn[i] << PAGE_SHIFT;
577 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
583 if ((dma->prot & prot) != prot) {
588 vpfn = vfio_iova_get_vfio_pfn(dma, iova);
590 phys_pfn[i] = vpfn->pfn;
594 remote_vaddr = dma->vaddr + iova - dma->iova;
595 ret = vfio_pin_page_external(dma, remote_vaddr, &phys_pfn[i],
600 ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
602 vfio_unpin_page_external(dma, iova, do_accounting);
612 for (j = 0; j < i; j++) {
615 iova = user_pfn[j] << PAGE_SHIFT;
616 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
617 vfio_unpin_page_external(dma, iova, do_accounting);
621 mutex_unlock(&iommu->lock);
625 static int vfio_iommu_type1_unpin_pages(void *iommu_data,
626 unsigned long *user_pfn,
629 struct vfio_iommu *iommu = iommu_data;
633 if (!iommu || !user_pfn)
636 /* Supported for v2 version only */
640 mutex_lock(&iommu->lock);
642 do_accounting = !IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu);
643 for (i = 0; i < npage; i++) {
644 struct vfio_dma *dma;
647 iova = user_pfn[i] << PAGE_SHIFT;
648 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
651 vfio_unpin_page_external(dma, iova, do_accounting);
655 mutex_unlock(&iommu->lock);
656 return i > npage ? npage : (i > 0 ? i : -EINVAL);
659 static long vfio_sync_unpin(struct vfio_dma *dma, struct vfio_domain *domain,
660 struct list_head *regions,
661 struct iommu_iotlb_gather *iotlb_gather)
664 struct vfio_regions *entry, *next;
666 iommu_tlb_sync(domain->domain, iotlb_gather);
668 list_for_each_entry_safe(entry, next, regions, list) {
669 unlocked += vfio_unpin_pages_remote(dma,
671 entry->phys >> PAGE_SHIFT,
672 entry->len >> PAGE_SHIFT,
674 list_del(&entry->list);
684 * Generally, VFIO needs to unpin remote pages after each IOTLB flush.
685 * Therefore, when using IOTLB flush sync interface, VFIO need to keep track
686 * of these regions (currently using a list).
688 * This value specifies maximum number of regions for each IOTLB flush sync.
690 #define VFIO_IOMMU_TLB_SYNC_MAX 512
692 static size_t unmap_unpin_fast(struct vfio_domain *domain,
693 struct vfio_dma *dma, dma_addr_t *iova,
694 size_t len, phys_addr_t phys, long *unlocked,
695 struct list_head *unmapped_list,
697 struct iommu_iotlb_gather *iotlb_gather)
700 struct vfio_regions *entry = kzalloc(sizeof(*entry), GFP_KERNEL);
703 unmapped = iommu_unmap_fast(domain->domain, *iova, len,
711 entry->len = unmapped;
712 list_add_tail(&entry->list, unmapped_list);
720 * Sync if the number of fast-unmap regions hits the limit
721 * or in case of errors.
723 if (*unmapped_cnt >= VFIO_IOMMU_TLB_SYNC_MAX || !unmapped) {
724 *unlocked += vfio_sync_unpin(dma, domain, unmapped_list,
732 static size_t unmap_unpin_slow(struct vfio_domain *domain,
733 struct vfio_dma *dma, dma_addr_t *iova,
734 size_t len, phys_addr_t phys,
737 size_t unmapped = iommu_unmap(domain->domain, *iova, len);
740 *unlocked += vfio_unpin_pages_remote(dma, *iova,
742 unmapped >> PAGE_SHIFT,
750 static long vfio_unmap_unpin(struct vfio_iommu *iommu, struct vfio_dma *dma,
753 dma_addr_t iova = dma->iova, end = dma->iova + dma->size;
754 struct vfio_domain *domain, *d;
755 LIST_HEAD(unmapped_region_list);
756 struct iommu_iotlb_gather iotlb_gather;
757 int unmapped_region_cnt = 0;
763 if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
767 * We use the IOMMU to track the physical addresses, otherwise we'd
768 * need a much more complicated tracking system. Unfortunately that
769 * means we need to use one of the iommu domains to figure out the
770 * pfns to unpin. The rest need to be unmapped in advance so we have
771 * no iommu translations remaining when the pages are unpinned.
773 domain = d = list_first_entry(&iommu->domain_list,
774 struct vfio_domain, next);
776 list_for_each_entry_continue(d, &iommu->domain_list, next) {
777 iommu_unmap(d->domain, dma->iova, dma->size);
781 iommu_iotlb_gather_init(&iotlb_gather);
783 size_t unmapped, len;
784 phys_addr_t phys, next;
786 phys = iommu_iova_to_phys(domain->domain, iova);
787 if (WARN_ON(!phys)) {
793 * To optimize for fewer iommu_unmap() calls, each of which
794 * may require hardware cache flushing, try to find the
795 * largest contiguous physical memory chunk to unmap.
797 for (len = PAGE_SIZE;
798 !domain->fgsp && iova + len < end; len += PAGE_SIZE) {
799 next = iommu_iova_to_phys(domain->domain, iova + len);
800 if (next != phys + len)
805 * First, try to use fast unmap/unpin. In case of failure,
806 * switch to slow unmap/unpin path.
808 unmapped = unmap_unpin_fast(domain, dma, &iova, len, phys,
809 &unlocked, &unmapped_region_list,
810 &unmapped_region_cnt,
813 unmapped = unmap_unpin_slow(domain, dma, &iova, len,
815 if (WARN_ON(!unmapped))
820 dma->iommu_mapped = false;
822 if (unmapped_region_cnt) {
823 unlocked += vfio_sync_unpin(dma, domain, &unmapped_region_list,
828 vfio_lock_acct(dma, -unlocked, true);
834 static void vfio_remove_dma(struct vfio_iommu *iommu, struct vfio_dma *dma)
836 vfio_unmap_unpin(iommu, dma, true);
837 vfio_unlink_dma(iommu, dma);
838 put_task_struct(dma->task);
843 static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
845 struct vfio_domain *domain;
846 unsigned long bitmap = ULONG_MAX;
848 mutex_lock(&iommu->lock);
849 list_for_each_entry(domain, &iommu->domain_list, next)
850 bitmap &= domain->domain->pgsize_bitmap;
851 mutex_unlock(&iommu->lock);
854 * In case the IOMMU supports page sizes smaller than PAGE_SIZE
855 * we pretend PAGE_SIZE is supported and hide sub-PAGE_SIZE sizes.
856 * That way the user will be able to map/unmap buffers whose size/
857 * start address is aligned with PAGE_SIZE. Pinning code uses that
858 * granularity while iommu driver can use the sub-PAGE_SIZE size
861 if (bitmap & ~PAGE_MASK) {
869 static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
870 struct vfio_iommu_type1_dma_unmap *unmap)
873 struct vfio_dma *dma, *dma_last = NULL;
875 int ret = 0, retries = 0;
877 mask = ((uint64_t)1 << __ffs(vfio_pgsize_bitmap(iommu))) - 1;
879 if (unmap->iova & mask)
881 if (!unmap->size || unmap->size & mask)
883 if (unmap->iova + unmap->size - 1 < unmap->iova ||
884 unmap->size > SIZE_MAX)
887 WARN_ON(mask & PAGE_MASK);
889 mutex_lock(&iommu->lock);
892 * vfio-iommu-type1 (v1) - User mappings were coalesced together to
893 * avoid tracking individual mappings. This means that the granularity
894 * of the original mapping was lost and the user was allowed to attempt
895 * to unmap any range. Depending on the contiguousness of physical
896 * memory and page sizes supported by the IOMMU, arbitrary unmaps may
897 * or may not have worked. We only guaranteed unmap granularity
898 * matching the original mapping; even though it was untracked here,
899 * the original mappings are reflected in IOMMU mappings. This
900 * resulted in a couple unusual behaviors. First, if a range is not
901 * able to be unmapped, ex. a set of 4k pages that was mapped as a
902 * 2M hugepage into the IOMMU, the unmap ioctl returns success but with
903 * a zero sized unmap. Also, if an unmap request overlaps the first
904 * address of a hugepage, the IOMMU will unmap the entire hugepage.
905 * This also returns success and the returned unmap size reflects the
906 * actual size unmapped.
908 * We attempt to maintain compatibility with this "v1" interface, but
909 * we take control out of the hands of the IOMMU. Therefore, an unmap
910 * request offset from the beginning of the original mapping will
911 * return success with zero sized unmap. And an unmap request covering
912 * the first iova of mapping will unmap the entire range.
914 * The v2 version of this interface intends to be more deterministic.
915 * Unmap requests must fully cover previous mappings. Multiple
916 * mappings may still be unmaped by specifying large ranges, but there
917 * must not be any previous mappings bisected by the range. An error
918 * will be returned if these conditions are not met. The v2 interface
919 * will only return success and a size of zero if there were no
920 * mappings within the range.
923 dma = vfio_find_dma(iommu, unmap->iova, 1);
924 if (dma && dma->iova != unmap->iova) {
928 dma = vfio_find_dma(iommu, unmap->iova + unmap->size - 1, 0);
929 if (dma && dma->iova + dma->size != unmap->iova + unmap->size) {
935 while ((dma = vfio_find_dma(iommu, unmap->iova, unmap->size))) {
936 if (!iommu->v2 && unmap->iova > dma->iova)
939 * Task with same address space who mapped this iova range is
940 * allowed to unmap the iova range.
942 if (dma->task->mm != current->mm)
945 if (!RB_EMPTY_ROOT(&dma->pfn_list)) {
946 struct vfio_iommu_type1_dma_unmap nb_unmap;
948 if (dma_last == dma) {
949 BUG_ON(++retries > 10);
955 nb_unmap.iova = dma->iova;
956 nb_unmap.size = dma->size;
959 * Notify anyone (mdev vendor drivers) to invalidate and
960 * unmap iovas within the range we're about to unmap.
961 * Vendor drivers MUST unpin pages in response to an
964 mutex_unlock(&iommu->lock);
965 blocking_notifier_call_chain(&iommu->notifier,
966 VFIO_IOMMU_NOTIFY_DMA_UNMAP,
970 unmapped += dma->size;
971 vfio_remove_dma(iommu, dma);
975 mutex_unlock(&iommu->lock);
977 /* Report how much was unmapped */
978 unmap->size = unmapped;
983 static int vfio_iommu_map(struct vfio_iommu *iommu, dma_addr_t iova,
984 unsigned long pfn, long npage, int prot)
986 struct vfio_domain *d;
989 list_for_each_entry(d, &iommu->domain_list, next) {
990 ret = iommu_map(d->domain, iova, (phys_addr_t)pfn << PAGE_SHIFT,
991 npage << PAGE_SHIFT, prot | d->prot);
1001 list_for_each_entry_continue_reverse(d, &iommu->domain_list, next)
1002 iommu_unmap(d->domain, iova, npage << PAGE_SHIFT);
1007 static int vfio_pin_map_dma(struct vfio_iommu *iommu, struct vfio_dma *dma,
1010 dma_addr_t iova = dma->iova;
1011 unsigned long vaddr = dma->vaddr;
1012 size_t size = map_size;
1014 unsigned long pfn, limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1018 /* Pin a contiguous chunk of memory */
1019 npage = vfio_pin_pages_remote(dma, vaddr + dma->size,
1020 size >> PAGE_SHIFT, &pfn, limit);
1028 ret = vfio_iommu_map(iommu, iova + dma->size, pfn, npage,
1031 vfio_unpin_pages_remote(dma, iova + dma->size, pfn,
1036 size -= npage << PAGE_SHIFT;
1037 dma->size += npage << PAGE_SHIFT;
1040 dma->iommu_mapped = true;
1043 vfio_remove_dma(iommu, dma);
1049 * Check dma map request is within a valid iova range
1051 static bool vfio_iommu_iova_dma_valid(struct vfio_iommu *iommu,
1052 dma_addr_t start, dma_addr_t end)
1054 struct list_head *iova = &iommu->iova_list;
1055 struct vfio_iova *node;
1057 list_for_each_entry(node, iova, list) {
1058 if (start >= node->start && end <= node->end)
1063 * Check for list_empty() as well since a container with
1064 * a single mdev device will have an empty list.
1066 return list_empty(iova);
1069 static int vfio_dma_do_map(struct vfio_iommu *iommu,
1070 struct vfio_iommu_type1_dma_map *map)
1072 dma_addr_t iova = map->iova;
1073 unsigned long vaddr = map->vaddr;
1074 size_t size = map->size;
1075 int ret = 0, prot = 0;
1077 struct vfio_dma *dma;
1079 /* Verify that none of our __u64 fields overflow */
1080 if (map->size != size || map->vaddr != vaddr || map->iova != iova)
1083 mask = ((uint64_t)1 << __ffs(vfio_pgsize_bitmap(iommu))) - 1;
1085 WARN_ON(mask & PAGE_MASK);
1087 /* READ/WRITE from device perspective */
1088 if (map->flags & VFIO_DMA_MAP_FLAG_WRITE)
1089 prot |= IOMMU_WRITE;
1090 if (map->flags & VFIO_DMA_MAP_FLAG_READ)
1093 if (!prot || !size || (size | iova | vaddr) & mask)
1096 /* Don't allow IOVA or virtual address wrap */
1097 if (iova + size - 1 < iova || vaddr + size - 1 < vaddr)
1100 mutex_lock(&iommu->lock);
1102 if (vfio_find_dma(iommu, iova, size)) {
1107 if (!iommu->dma_avail) {
1112 if (!vfio_iommu_iova_dma_valid(iommu, iova, iova + size - 1)) {
1117 dma = kzalloc(sizeof(*dma), GFP_KERNEL);
1129 * We need to be able to both add to a task's locked memory and test
1130 * against the locked memory limit and we need to be able to do both
1131 * outside of this call path as pinning can be asynchronous via the
1132 * external interfaces for mdev devices. RLIMIT_MEMLOCK requires a
1133 * task_struct and VM locked pages requires an mm_struct, however
1134 * holding an indefinite mm reference is not recommended, therefore we
1135 * only hold a reference to a task. We could hold a reference to
1136 * current, however QEMU uses this call path through vCPU threads,
1137 * which can be killed resulting in a NULL mm and failure in the unmap
1138 * path when called via a different thread. Avoid this problem by
1139 * using the group_leader as threads within the same group require
1140 * both CLONE_THREAD and CLONE_VM and will therefore use the same
1143 * Previously we also used the task for testing CAP_IPC_LOCK at the
1144 * time of pinning and accounting, however has_capability() makes use
1145 * of real_cred, a copy-on-write field, so we can't guarantee that it
1146 * matches group_leader, or in fact that it might not change by the
1147 * time it's evaluated. If a process were to call MAP_DMA with
1148 * CAP_IPC_LOCK but later drop it, it doesn't make sense that they
1149 * possibly see different results for an iommu_mapped vfio_dma vs
1150 * externally mapped. Therefore track CAP_IPC_LOCK in vfio_dma at the
1151 * time of calling MAP_DMA.
1153 get_task_struct(current->group_leader);
1154 dma->task = current->group_leader;
1155 dma->lock_cap = capable(CAP_IPC_LOCK);
1157 dma->pfn_list = RB_ROOT;
1159 /* Insert zero-sized and grow as we map chunks of it */
1160 vfio_link_dma(iommu, dma);
1162 /* Don't pin and map if container doesn't contain IOMMU capable domain*/
1163 if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
1166 ret = vfio_pin_map_dma(iommu, dma, size);
1169 mutex_unlock(&iommu->lock);
1173 static int vfio_bus_type(struct device *dev, void *data)
1175 struct bus_type **bus = data;
1177 if (*bus && *bus != dev->bus)
1185 static int vfio_iommu_replay(struct vfio_iommu *iommu,
1186 struct vfio_domain *domain)
1188 struct vfio_domain *d;
1190 unsigned long limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1193 /* Arbitrarily pick the first domain in the list for lookups */
1194 d = list_first_entry(&iommu->domain_list, struct vfio_domain, next);
1195 n = rb_first(&iommu->dma_list);
1197 for (; n; n = rb_next(n)) {
1198 struct vfio_dma *dma;
1201 dma = rb_entry(n, struct vfio_dma, node);
1204 while (iova < dma->iova + dma->size) {
1208 if (dma->iommu_mapped) {
1212 phys = iommu_iova_to_phys(d->domain, iova);
1214 if (WARN_ON(!phys)) {
1222 while (i < dma->iova + dma->size &&
1223 p == iommu_iova_to_phys(d->domain, i)) {
1230 unsigned long vaddr = dma->vaddr +
1232 size_t n = dma->iova + dma->size - iova;
1235 npage = vfio_pin_pages_remote(dma, vaddr,
1244 phys = pfn << PAGE_SHIFT;
1245 size = npage << PAGE_SHIFT;
1248 ret = iommu_map(domain->domain, iova, phys,
1249 size, dma->prot | domain->prot);
1255 dma->iommu_mapped = true;
1261 * We change our unmap behavior slightly depending on whether the IOMMU
1262 * supports fine-grained superpages. IOMMUs like AMD-Vi will use a superpage
1263 * for practically any contiguous power-of-two mapping we give it. This means
1264 * we don't need to look for contiguous chunks ourselves to make unmapping
1265 * more efficient. On IOMMUs with coarse-grained super pages, like Intel VT-d
1266 * with discrete 2M/1G/512G/1T superpages, identifying contiguous chunks
1267 * significantly boosts non-hugetlbfs mappings and doesn't seem to hurt when
1268 * hugetlbfs is in use.
1270 static void vfio_test_domain_fgsp(struct vfio_domain *domain)
1273 int ret, order = get_order(PAGE_SIZE * 2);
1275 pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, order);
1279 ret = iommu_map(domain->domain, 0, page_to_phys(pages), PAGE_SIZE * 2,
1280 IOMMU_READ | IOMMU_WRITE | domain->prot);
1282 size_t unmapped = iommu_unmap(domain->domain, 0, PAGE_SIZE);
1284 if (unmapped == PAGE_SIZE)
1285 iommu_unmap(domain->domain, PAGE_SIZE, PAGE_SIZE);
1287 domain->fgsp = true;
1290 __free_pages(pages, order);
1293 static struct vfio_group *find_iommu_group(struct vfio_domain *domain,
1294 struct iommu_group *iommu_group)
1296 struct vfio_group *g;
1298 list_for_each_entry(g, &domain->group_list, next) {
1299 if (g->iommu_group == iommu_group)
1306 static bool vfio_iommu_has_sw_msi(struct list_head *group_resv_regions,
1309 struct iommu_resv_region *region;
1312 list_for_each_entry(region, group_resv_regions, list) {
1314 * The presence of any 'real' MSI regions should take
1315 * precedence over the software-managed one if the
1316 * IOMMU driver happens to advertise both types.
1318 if (region->type == IOMMU_RESV_MSI) {
1323 if (region->type == IOMMU_RESV_SW_MSI) {
1324 *base = region->start;
1332 static struct device *vfio_mdev_get_iommu_device(struct device *dev)
1334 struct device *(*fn)(struct device *dev);
1335 struct device *iommu_device;
1337 fn = symbol_get(mdev_get_iommu_device);
1339 iommu_device = fn(dev);
1340 symbol_put(mdev_get_iommu_device);
1342 return iommu_device;
1348 static int vfio_mdev_attach_domain(struct device *dev, void *data)
1350 struct iommu_domain *domain = data;
1351 struct device *iommu_device;
1353 iommu_device = vfio_mdev_get_iommu_device(dev);
1355 if (iommu_dev_feature_enabled(iommu_device, IOMMU_DEV_FEAT_AUX))
1356 return iommu_aux_attach_device(domain, iommu_device);
1358 return iommu_attach_device(domain, iommu_device);
1364 static int vfio_mdev_detach_domain(struct device *dev, void *data)
1366 struct iommu_domain *domain = data;
1367 struct device *iommu_device;
1369 iommu_device = vfio_mdev_get_iommu_device(dev);
1371 if (iommu_dev_feature_enabled(iommu_device, IOMMU_DEV_FEAT_AUX))
1372 iommu_aux_detach_device(domain, iommu_device);
1374 iommu_detach_device(domain, iommu_device);
1380 static int vfio_iommu_attach_group(struct vfio_domain *domain,
1381 struct vfio_group *group)
1383 if (group->mdev_group)
1384 return iommu_group_for_each_dev(group->iommu_group,
1386 vfio_mdev_attach_domain);
1388 return iommu_attach_group(domain->domain, group->iommu_group);
1391 static void vfio_iommu_detach_group(struct vfio_domain *domain,
1392 struct vfio_group *group)
1394 if (group->mdev_group)
1395 iommu_group_for_each_dev(group->iommu_group, domain->domain,
1396 vfio_mdev_detach_domain);
1398 iommu_detach_group(domain->domain, group->iommu_group);
1401 static bool vfio_bus_is_mdev(struct bus_type *bus)
1403 struct bus_type *mdev_bus;
1406 mdev_bus = symbol_get(mdev_bus_type);
1408 ret = (bus == mdev_bus);
1409 symbol_put(mdev_bus_type);
1415 static int vfio_mdev_iommu_device(struct device *dev, void *data)
1417 struct device **old = data, *new;
1419 new = vfio_mdev_get_iommu_device(dev);
1420 if (!new || (*old && *old != new))
1429 * This is a helper function to insert an address range to iova list.
1430 * The list is initially created with a single entry corresponding to
1431 * the IOMMU domain geometry to which the device group is attached.
1432 * The list aperture gets modified when a new domain is added to the
1433 * container if the new aperture doesn't conflict with the current one
1434 * or with any existing dma mappings. The list is also modified to
1435 * exclude any reserved regions associated with the device group.
1437 static int vfio_iommu_iova_insert(struct list_head *head,
1438 dma_addr_t start, dma_addr_t end)
1440 struct vfio_iova *region;
1442 region = kmalloc(sizeof(*region), GFP_KERNEL);
1446 INIT_LIST_HEAD(®ion->list);
1447 region->start = start;
1450 list_add_tail(®ion->list, head);
1455 * Check the new iommu aperture conflicts with existing aper or with any
1456 * existing dma mappings.
1458 static bool vfio_iommu_aper_conflict(struct vfio_iommu *iommu,
1459 dma_addr_t start, dma_addr_t end)
1461 struct vfio_iova *first, *last;
1462 struct list_head *iova = &iommu->iova_list;
1464 if (list_empty(iova))
1467 /* Disjoint sets, return conflict */
1468 first = list_first_entry(iova, struct vfio_iova, list);
1469 last = list_last_entry(iova, struct vfio_iova, list);
1470 if (start > last->end || end < first->start)
1473 /* Check for any existing dma mappings below the new start */
1474 if (start > first->start) {
1475 if (vfio_find_dma(iommu, first->start, start - first->start))
1479 /* Check for any existing dma mappings beyond the new end */
1480 if (end < last->end) {
1481 if (vfio_find_dma(iommu, end + 1, last->end - end))
1489 * Resize iommu iova aperture window. This is called only if the new
1490 * aperture has no conflict with existing aperture and dma mappings.
1492 static int vfio_iommu_aper_resize(struct list_head *iova,
1493 dma_addr_t start, dma_addr_t end)
1495 struct vfio_iova *node, *next;
1497 if (list_empty(iova))
1498 return vfio_iommu_iova_insert(iova, start, end);
1500 /* Adjust iova list start */
1501 list_for_each_entry_safe(node, next, iova, list) {
1502 if (start < node->start)
1504 if (start >= node->start && start < node->end) {
1505 node->start = start;
1508 /* Delete nodes before new start */
1509 list_del(&node->list);
1513 /* Adjust iova list end */
1514 list_for_each_entry_safe(node, next, iova, list) {
1515 if (end > node->end)
1517 if (end > node->start && end <= node->end) {
1521 /* Delete nodes after new end */
1522 list_del(&node->list);
1530 * Check reserved region conflicts with existing dma mappings
1532 static bool vfio_iommu_resv_conflict(struct vfio_iommu *iommu,
1533 struct list_head *resv_regions)
1535 struct iommu_resv_region *region;
1537 /* Check for conflict with existing dma mappings */
1538 list_for_each_entry(region, resv_regions, list) {
1539 if (region->type == IOMMU_RESV_DIRECT_RELAXABLE)
1542 if (vfio_find_dma(iommu, region->start, region->length))
1550 * Check iova region overlap with reserved regions and
1551 * exclude them from the iommu iova range
1553 static int vfio_iommu_resv_exclude(struct list_head *iova,
1554 struct list_head *resv_regions)
1556 struct iommu_resv_region *resv;
1557 struct vfio_iova *n, *next;
1559 list_for_each_entry(resv, resv_regions, list) {
1560 phys_addr_t start, end;
1562 if (resv->type == IOMMU_RESV_DIRECT_RELAXABLE)
1565 start = resv->start;
1566 end = resv->start + resv->length - 1;
1568 list_for_each_entry_safe(n, next, iova, list) {
1572 if (start > n->end || end < n->start)
1575 * Insert a new node if current node overlaps with the
1576 * reserve region to exlude that from valid iova range.
1577 * Note that, new node is inserted before the current
1578 * node and finally the current node is deleted keeping
1579 * the list updated and sorted.
1581 if (start > n->start)
1582 ret = vfio_iommu_iova_insert(&n->list, n->start,
1584 if (!ret && end < n->end)
1585 ret = vfio_iommu_iova_insert(&n->list, end + 1,
1595 if (list_empty(iova))
1601 static void vfio_iommu_resv_free(struct list_head *resv_regions)
1603 struct iommu_resv_region *n, *next;
1605 list_for_each_entry_safe(n, next, resv_regions, list) {
1611 static void vfio_iommu_iova_free(struct list_head *iova)
1613 struct vfio_iova *n, *next;
1615 list_for_each_entry_safe(n, next, iova, list) {
1621 static int vfio_iommu_iova_get_copy(struct vfio_iommu *iommu,
1622 struct list_head *iova_copy)
1624 struct list_head *iova = &iommu->iova_list;
1625 struct vfio_iova *n;
1628 list_for_each_entry(n, iova, list) {
1629 ret = vfio_iommu_iova_insert(iova_copy, n->start, n->end);
1637 vfio_iommu_iova_free(iova_copy);
1641 static void vfio_iommu_iova_insert_copy(struct vfio_iommu *iommu,
1642 struct list_head *iova_copy)
1644 struct list_head *iova = &iommu->iova_list;
1646 vfio_iommu_iova_free(iova);
1648 list_splice_tail(iova_copy, iova);
1650 static int vfio_iommu_type1_attach_group(void *iommu_data,
1651 struct iommu_group *iommu_group)
1653 struct vfio_iommu *iommu = iommu_data;
1654 struct vfio_group *group;
1655 struct vfio_domain *domain, *d;
1656 struct bus_type *bus = NULL;
1658 bool resv_msi, msi_remap;
1659 phys_addr_t resv_msi_base;
1660 struct iommu_domain_geometry geo;
1661 LIST_HEAD(iova_copy);
1662 LIST_HEAD(group_resv_regions);
1664 mutex_lock(&iommu->lock);
1666 list_for_each_entry(d, &iommu->domain_list, next) {
1667 if (find_iommu_group(d, iommu_group)) {
1668 mutex_unlock(&iommu->lock);
1673 if (iommu->external_domain) {
1674 if (find_iommu_group(iommu->external_domain, iommu_group)) {
1675 mutex_unlock(&iommu->lock);
1680 group = kzalloc(sizeof(*group), GFP_KERNEL);
1681 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
1682 if (!group || !domain) {
1687 group->iommu_group = iommu_group;
1689 /* Determine bus_type in order to allocate a domain */
1690 ret = iommu_group_for_each_dev(iommu_group, &bus, vfio_bus_type);
1694 if (vfio_bus_is_mdev(bus)) {
1695 struct device *iommu_device = NULL;
1697 group->mdev_group = true;
1699 /* Determine the isolation type */
1700 ret = iommu_group_for_each_dev(iommu_group, &iommu_device,
1701 vfio_mdev_iommu_device);
1702 if (ret || !iommu_device) {
1703 if (!iommu->external_domain) {
1704 INIT_LIST_HEAD(&domain->group_list);
1705 iommu->external_domain = domain;
1710 list_add(&group->next,
1711 &iommu->external_domain->group_list);
1712 mutex_unlock(&iommu->lock);
1717 bus = iommu_device->bus;
1720 domain->domain = iommu_domain_alloc(bus);
1721 if (!domain->domain) {
1726 if (iommu->nesting) {
1729 ret = iommu_domain_set_attr(domain->domain, DOMAIN_ATTR_NESTING,
1735 ret = vfio_iommu_attach_group(domain, group);
1739 /* Get aperture info */
1740 iommu_domain_get_attr(domain->domain, DOMAIN_ATTR_GEOMETRY, &geo);
1742 if (vfio_iommu_aper_conflict(iommu, geo.aperture_start,
1743 geo.aperture_end)) {
1748 ret = iommu_get_group_resv_regions(iommu_group, &group_resv_regions);
1752 if (vfio_iommu_resv_conflict(iommu, &group_resv_regions)) {
1758 * We don't want to work on the original iova list as the list
1759 * gets modified and in case of failure we have to retain the
1760 * original list. Get a copy here.
1762 ret = vfio_iommu_iova_get_copy(iommu, &iova_copy);
1766 ret = vfio_iommu_aper_resize(&iova_copy, geo.aperture_start,
1771 ret = vfio_iommu_resv_exclude(&iova_copy, &group_resv_regions);
1775 resv_msi = vfio_iommu_has_sw_msi(&group_resv_regions, &resv_msi_base);
1777 INIT_LIST_HEAD(&domain->group_list);
1778 list_add(&group->next, &domain->group_list);
1780 msi_remap = irq_domain_check_msi_remap() ||
1781 iommu_capable(bus, IOMMU_CAP_INTR_REMAP);
1783 if (!allow_unsafe_interrupts && !msi_remap) {
1784 pr_warn("%s: No interrupt remapping support. Use the module param \"allow_unsafe_interrupts\" to enable VFIO IOMMU support on this platform\n",
1790 if (iommu_capable(bus, IOMMU_CAP_CACHE_COHERENCY))
1791 domain->prot |= IOMMU_CACHE;
1794 * Try to match an existing compatible domain. We don't want to
1795 * preclude an IOMMU driver supporting multiple bus_types and being
1796 * able to include different bus_types in the same IOMMU domain, so
1797 * we test whether the domains use the same iommu_ops rather than
1798 * testing if they're on the same bus_type.
1800 list_for_each_entry(d, &iommu->domain_list, next) {
1801 if (d->domain->ops == domain->domain->ops &&
1802 d->prot == domain->prot) {
1803 vfio_iommu_detach_group(domain, group);
1804 if (!vfio_iommu_attach_group(d, group)) {
1805 list_add(&group->next, &d->group_list);
1806 iommu_domain_free(domain->domain);
1811 ret = vfio_iommu_attach_group(domain, group);
1817 vfio_test_domain_fgsp(domain);
1819 /* replay mappings on new domains */
1820 ret = vfio_iommu_replay(iommu, domain);
1825 ret = iommu_get_msi_cookie(domain->domain, resv_msi_base);
1830 list_add(&domain->next, &iommu->domain_list);
1832 /* Delete the old one and insert new iova list */
1833 vfio_iommu_iova_insert_copy(iommu, &iova_copy);
1834 mutex_unlock(&iommu->lock);
1835 vfio_iommu_resv_free(&group_resv_regions);
1840 vfio_iommu_detach_group(domain, group);
1842 iommu_domain_free(domain->domain);
1843 vfio_iommu_iova_free(&iova_copy);
1844 vfio_iommu_resv_free(&group_resv_regions);
1848 mutex_unlock(&iommu->lock);
1852 static void vfio_iommu_unmap_unpin_all(struct vfio_iommu *iommu)
1854 struct rb_node *node;
1856 while ((node = rb_first(&iommu->dma_list)))
1857 vfio_remove_dma(iommu, rb_entry(node, struct vfio_dma, node));
1860 static void vfio_iommu_unmap_unpin_reaccount(struct vfio_iommu *iommu)
1862 struct rb_node *n, *p;
1864 n = rb_first(&iommu->dma_list);
1865 for (; n; n = rb_next(n)) {
1866 struct vfio_dma *dma;
1867 long locked = 0, unlocked = 0;
1869 dma = rb_entry(n, struct vfio_dma, node);
1870 unlocked += vfio_unmap_unpin(iommu, dma, false);
1871 p = rb_first(&dma->pfn_list);
1872 for (; p; p = rb_next(p)) {
1873 struct vfio_pfn *vpfn = rb_entry(p, struct vfio_pfn,
1876 if (!is_invalid_reserved_pfn(vpfn->pfn))
1879 vfio_lock_acct(dma, locked - unlocked, true);
1883 static void vfio_sanity_check_pfn_list(struct vfio_iommu *iommu)
1887 n = rb_first(&iommu->dma_list);
1888 for (; n; n = rb_next(n)) {
1889 struct vfio_dma *dma;
1891 dma = rb_entry(n, struct vfio_dma, node);
1893 if (WARN_ON(!RB_EMPTY_ROOT(&dma->pfn_list)))
1896 /* mdev vendor driver must unregister notifier */
1897 WARN_ON(iommu->notifier.head);
1901 * Called when a domain is removed in detach. It is possible that
1902 * the removed domain decided the iova aperture window. Modify the
1903 * iova aperture with the smallest window among existing domains.
1905 static void vfio_iommu_aper_expand(struct vfio_iommu *iommu,
1906 struct list_head *iova_copy)
1908 struct vfio_domain *domain;
1909 struct iommu_domain_geometry geo;
1910 struct vfio_iova *node;
1911 dma_addr_t start = 0;
1912 dma_addr_t end = (dma_addr_t)~0;
1914 if (list_empty(iova_copy))
1917 list_for_each_entry(domain, &iommu->domain_list, next) {
1918 iommu_domain_get_attr(domain->domain, DOMAIN_ATTR_GEOMETRY,
1920 if (geo.aperture_start > start)
1921 start = geo.aperture_start;
1922 if (geo.aperture_end < end)
1923 end = geo.aperture_end;
1926 /* Modify aperture limits. The new aper is either same or bigger */
1927 node = list_first_entry(iova_copy, struct vfio_iova, list);
1928 node->start = start;
1929 node = list_last_entry(iova_copy, struct vfio_iova, list);
1934 * Called when a group is detached. The reserved regions for that
1935 * group can be part of valid iova now. But since reserved regions
1936 * may be duplicated among groups, populate the iova valid regions
1939 static int vfio_iommu_resv_refresh(struct vfio_iommu *iommu,
1940 struct list_head *iova_copy)
1942 struct vfio_domain *d;
1943 struct vfio_group *g;
1944 struct vfio_iova *node;
1945 dma_addr_t start, end;
1946 LIST_HEAD(resv_regions);
1949 if (list_empty(iova_copy))
1952 list_for_each_entry(d, &iommu->domain_list, next) {
1953 list_for_each_entry(g, &d->group_list, next) {
1954 ret = iommu_get_group_resv_regions(g->iommu_group,
1961 node = list_first_entry(iova_copy, struct vfio_iova, list);
1962 start = node->start;
1963 node = list_last_entry(iova_copy, struct vfio_iova, list);
1966 /* purge the iova list and create new one */
1967 vfio_iommu_iova_free(iova_copy);
1969 ret = vfio_iommu_aper_resize(iova_copy, start, end);
1973 /* Exclude current reserved regions from iova ranges */
1974 ret = vfio_iommu_resv_exclude(iova_copy, &resv_regions);
1976 vfio_iommu_resv_free(&resv_regions);
1980 static void vfio_iommu_type1_detach_group(void *iommu_data,
1981 struct iommu_group *iommu_group)
1983 struct vfio_iommu *iommu = iommu_data;
1984 struct vfio_domain *domain;
1985 struct vfio_group *group;
1986 LIST_HEAD(iova_copy);
1988 mutex_lock(&iommu->lock);
1990 if (iommu->external_domain) {
1991 group = find_iommu_group(iommu->external_domain, iommu_group);
1993 list_del(&group->next);
1996 if (list_empty(&iommu->external_domain->group_list)) {
1997 vfio_sanity_check_pfn_list(iommu);
1999 if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
2000 vfio_iommu_unmap_unpin_all(iommu);
2002 kfree(iommu->external_domain);
2003 iommu->external_domain = NULL;
2005 goto detach_group_done;
2010 * Get a copy of iova list. This will be used to update
2011 * and to replace the current one later. Please note that
2012 * we will leave the original list as it is if update fails.
2014 vfio_iommu_iova_get_copy(iommu, &iova_copy);
2016 list_for_each_entry(domain, &iommu->domain_list, next) {
2017 group = find_iommu_group(domain, iommu_group);
2021 vfio_iommu_detach_group(domain, group);
2022 list_del(&group->next);
2025 * Group ownership provides privilege, if the group list is
2026 * empty, the domain goes away. If it's the last domain with
2027 * iommu and external domain doesn't exist, then all the
2028 * mappings go away too. If it's the last domain with iommu and
2029 * external domain exist, update accounting
2031 if (list_empty(&domain->group_list)) {
2032 if (list_is_singular(&iommu->domain_list)) {
2033 if (!iommu->external_domain)
2034 vfio_iommu_unmap_unpin_all(iommu);
2036 vfio_iommu_unmap_unpin_reaccount(iommu);
2038 iommu_domain_free(domain->domain);
2039 list_del(&domain->next);
2041 vfio_iommu_aper_expand(iommu, &iova_copy);
2046 if (!vfio_iommu_resv_refresh(iommu, &iova_copy))
2047 vfio_iommu_iova_insert_copy(iommu, &iova_copy);
2049 vfio_iommu_iova_free(&iova_copy);
2052 mutex_unlock(&iommu->lock);
2055 static void *vfio_iommu_type1_open(unsigned long arg)
2057 struct vfio_iommu *iommu;
2059 iommu = kzalloc(sizeof(*iommu), GFP_KERNEL);
2061 return ERR_PTR(-ENOMEM);
2064 case VFIO_TYPE1_IOMMU:
2066 case VFIO_TYPE1_NESTING_IOMMU:
2067 iommu->nesting = true;
2069 case VFIO_TYPE1v2_IOMMU:
2074 return ERR_PTR(-EINVAL);
2077 INIT_LIST_HEAD(&iommu->domain_list);
2078 INIT_LIST_HEAD(&iommu->iova_list);
2079 iommu->dma_list = RB_ROOT;
2080 iommu->dma_avail = dma_entry_limit;
2081 mutex_init(&iommu->lock);
2082 BLOCKING_INIT_NOTIFIER_HEAD(&iommu->notifier);
2087 static void vfio_release_domain(struct vfio_domain *domain, bool external)
2089 struct vfio_group *group, *group_tmp;
2091 list_for_each_entry_safe(group, group_tmp,
2092 &domain->group_list, next) {
2094 vfio_iommu_detach_group(domain, group);
2095 list_del(&group->next);
2100 iommu_domain_free(domain->domain);
2103 static void vfio_iommu_type1_release(void *iommu_data)
2105 struct vfio_iommu *iommu = iommu_data;
2106 struct vfio_domain *domain, *domain_tmp;
2108 if (iommu->external_domain) {
2109 vfio_release_domain(iommu->external_domain, true);
2110 vfio_sanity_check_pfn_list(iommu);
2111 kfree(iommu->external_domain);
2114 vfio_iommu_unmap_unpin_all(iommu);
2116 list_for_each_entry_safe(domain, domain_tmp,
2117 &iommu->domain_list, next) {
2118 vfio_release_domain(domain, false);
2119 list_del(&domain->next);
2123 vfio_iommu_iova_free(&iommu->iova_list);
2128 static int vfio_domains_have_iommu_cache(struct vfio_iommu *iommu)
2130 struct vfio_domain *domain;
2133 mutex_lock(&iommu->lock);
2134 list_for_each_entry(domain, &iommu->domain_list, next) {
2135 if (!(domain->prot & IOMMU_CACHE)) {
2140 mutex_unlock(&iommu->lock);
2145 static int vfio_iommu_iova_add_cap(struct vfio_info_cap *caps,
2146 struct vfio_iommu_type1_info_cap_iova_range *cap_iovas,
2149 struct vfio_info_cap_header *header;
2150 struct vfio_iommu_type1_info_cap_iova_range *iova_cap;
2152 header = vfio_info_cap_add(caps, size,
2153 VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE, 1);
2155 return PTR_ERR(header);
2157 iova_cap = container_of(header,
2158 struct vfio_iommu_type1_info_cap_iova_range,
2160 iova_cap->nr_iovas = cap_iovas->nr_iovas;
2161 memcpy(iova_cap->iova_ranges, cap_iovas->iova_ranges,
2162 cap_iovas->nr_iovas * sizeof(*cap_iovas->iova_ranges));
2166 static int vfio_iommu_iova_build_caps(struct vfio_iommu *iommu,
2167 struct vfio_info_cap *caps)
2169 struct vfio_iommu_type1_info_cap_iova_range *cap_iovas;
2170 struct vfio_iova *iova;
2172 int iovas = 0, i = 0, ret;
2174 mutex_lock(&iommu->lock);
2176 list_for_each_entry(iova, &iommu->iova_list, list)
2181 * Return 0 as a container with a single mdev device
2182 * will have an empty list
2188 size = sizeof(*cap_iovas) + (iovas * sizeof(*cap_iovas->iova_ranges));
2190 cap_iovas = kzalloc(size, GFP_KERNEL);
2196 cap_iovas->nr_iovas = iovas;
2198 list_for_each_entry(iova, &iommu->iova_list, list) {
2199 cap_iovas->iova_ranges[i].start = iova->start;
2200 cap_iovas->iova_ranges[i].end = iova->end;
2204 ret = vfio_iommu_iova_add_cap(caps, cap_iovas, size);
2208 mutex_unlock(&iommu->lock);
2212 static long vfio_iommu_type1_ioctl(void *iommu_data,
2213 unsigned int cmd, unsigned long arg)
2215 struct vfio_iommu *iommu = iommu_data;
2216 unsigned long minsz;
2218 if (cmd == VFIO_CHECK_EXTENSION) {
2220 case VFIO_TYPE1_IOMMU:
2221 case VFIO_TYPE1v2_IOMMU:
2222 case VFIO_TYPE1_NESTING_IOMMU:
2224 case VFIO_DMA_CC_IOMMU:
2227 return vfio_domains_have_iommu_cache(iommu);
2231 } else if (cmd == VFIO_IOMMU_GET_INFO) {
2232 struct vfio_iommu_type1_info info;
2233 struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
2234 unsigned long capsz;
2237 minsz = offsetofend(struct vfio_iommu_type1_info, iova_pgsizes);
2239 /* For backward compatibility, cannot require this */
2240 capsz = offsetofend(struct vfio_iommu_type1_info, cap_offset);
2242 if (copy_from_user(&info, (void __user *)arg, minsz))
2245 if (info.argsz < minsz)
2248 if (info.argsz >= capsz) {
2250 info.cap_offset = 0; /* output, no-recopy necessary */
2253 info.flags = VFIO_IOMMU_INFO_PGSIZES;
2255 info.iova_pgsizes = vfio_pgsize_bitmap(iommu);
2257 ret = vfio_iommu_iova_build_caps(iommu, &caps);
2262 info.flags |= VFIO_IOMMU_INFO_CAPS;
2264 if (info.argsz < sizeof(info) + caps.size) {
2265 info.argsz = sizeof(info) + caps.size;
2267 vfio_info_cap_shift(&caps, sizeof(info));
2268 if (copy_to_user((void __user *)arg +
2269 sizeof(info), caps.buf,
2274 info.cap_offset = sizeof(info);
2280 return copy_to_user((void __user *)arg, &info, minsz) ?
2283 } else if (cmd == VFIO_IOMMU_MAP_DMA) {
2284 struct vfio_iommu_type1_dma_map map;
2285 uint32_t mask = VFIO_DMA_MAP_FLAG_READ |
2286 VFIO_DMA_MAP_FLAG_WRITE;
2288 minsz = offsetofend(struct vfio_iommu_type1_dma_map, size);
2290 if (copy_from_user(&map, (void __user *)arg, minsz))
2293 if (map.argsz < minsz || map.flags & ~mask)
2296 return vfio_dma_do_map(iommu, &map);
2298 } else if (cmd == VFIO_IOMMU_UNMAP_DMA) {
2299 struct vfio_iommu_type1_dma_unmap unmap;
2302 minsz = offsetofend(struct vfio_iommu_type1_dma_unmap, size);
2304 if (copy_from_user(&unmap, (void __user *)arg, minsz))
2307 if (unmap.argsz < minsz || unmap.flags)
2310 ret = vfio_dma_do_unmap(iommu, &unmap);
2314 return copy_to_user((void __user *)arg, &unmap, minsz) ?
2321 static int vfio_iommu_type1_register_notifier(void *iommu_data,
2322 unsigned long *events,
2323 struct notifier_block *nb)
2325 struct vfio_iommu *iommu = iommu_data;
2327 /* clear known events */
2328 *events &= ~VFIO_IOMMU_NOTIFY_DMA_UNMAP;
2330 /* refuse to register if still events remaining */
2334 return blocking_notifier_chain_register(&iommu->notifier, nb);
2337 static int vfio_iommu_type1_unregister_notifier(void *iommu_data,
2338 struct notifier_block *nb)
2340 struct vfio_iommu *iommu = iommu_data;
2342 return blocking_notifier_chain_unregister(&iommu->notifier, nb);
2345 static const struct vfio_iommu_driver_ops vfio_iommu_driver_ops_type1 = {
2346 .name = "vfio-iommu-type1",
2347 .owner = THIS_MODULE,
2348 .open = vfio_iommu_type1_open,
2349 .release = vfio_iommu_type1_release,
2350 .ioctl = vfio_iommu_type1_ioctl,
2351 .attach_group = vfio_iommu_type1_attach_group,
2352 .detach_group = vfio_iommu_type1_detach_group,
2353 .pin_pages = vfio_iommu_type1_pin_pages,
2354 .unpin_pages = vfio_iommu_type1_unpin_pages,
2355 .register_notifier = vfio_iommu_type1_register_notifier,
2356 .unregister_notifier = vfio_iommu_type1_unregister_notifier,
2359 static int __init vfio_iommu_type1_init(void)
2361 return vfio_register_iommu_driver(&vfio_iommu_driver_ops_type1);
2364 static void __exit vfio_iommu_type1_cleanup(void)
2366 vfio_unregister_iommu_driver(&vfio_iommu_driver_ops_type1);
2369 module_init(vfio_iommu_type1_init);
2370 module_exit(vfio_iommu_type1_cleanup);
2372 MODULE_VERSION(DRIVER_VERSION);
2373 MODULE_LICENSE("GPL v2");
2374 MODULE_AUTHOR(DRIVER_AUTHOR);
2375 MODULE_DESCRIPTION(DRIVER_DESC);