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/mmu_context.h>
31 #include <linux/rbtree.h>
32 #include <linux/sched/signal.h>
33 #include <linux/sched/mm.h>
34 #include <linux/slab.h>
35 #include <linux/uaccess.h>
36 #include <linux/vfio.h>
37 #include <linux/workqueue.h>
38 #include <linux/mdev.h>
39 #include <linux/notifier.h>
40 #include <linux/dma-iommu.h>
41 #include <linux/irqdomain.h>
43 #define DRIVER_VERSION "0.2"
44 #define DRIVER_AUTHOR "Alex Williamson <alex.williamson@redhat.com>"
45 #define DRIVER_DESC "Type1 IOMMU driver for VFIO"
47 static bool allow_unsafe_interrupts;
48 module_param_named(allow_unsafe_interrupts,
49 allow_unsafe_interrupts, bool, S_IRUGO | S_IWUSR);
50 MODULE_PARM_DESC(allow_unsafe_interrupts,
51 "Enable VFIO IOMMU support for on platforms without interrupt remapping support.");
53 static bool disable_hugepages;
54 module_param_named(disable_hugepages,
55 disable_hugepages, bool, S_IRUGO | S_IWUSR);
56 MODULE_PARM_DESC(disable_hugepages,
57 "Disable VFIO IOMMU support for IOMMU hugepages.");
59 static unsigned int dma_entry_limit __read_mostly = U16_MAX;
60 module_param_named(dma_entry_limit, dma_entry_limit, uint, 0644);
61 MODULE_PARM_DESC(dma_entry_limit,
62 "Maximum number of user DMA mappings per container (65535).");
65 struct list_head domain_list;
66 struct list_head iova_list;
67 struct vfio_domain *external_domain; /* domain for external user */
69 struct rb_root dma_list;
70 struct blocking_notifier_head notifier;
71 unsigned int dma_avail;
77 struct iommu_domain *domain;
78 struct list_head next;
79 struct list_head group_list;
80 int prot; /* IOMMU_CACHE */
81 bool fgsp; /* Fine-grained super pages */
86 dma_addr_t iova; /* Device address */
87 unsigned long vaddr; /* Process virtual addr */
88 size_t size; /* Map size (bytes) */
89 int prot; /* IOMMU_READ/WRITE */
91 bool lock_cap; /* capable(CAP_IPC_LOCK) */
92 struct task_struct *task;
93 struct rb_root pfn_list; /* Ex-user pinned pfn list */
97 struct iommu_group *iommu_group;
98 struct list_head next;
99 bool mdev_group; /* An mdev group */
103 struct list_head list;
109 * Guest RAM pinning working set or DMA target
113 dma_addr_t iova; /* Device address */
114 unsigned long pfn; /* Host pfn */
118 struct vfio_regions {
119 struct list_head list;
125 #define IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu) \
126 (!list_empty(&iommu->domain_list))
128 static int put_pfn(unsigned long pfn, int prot);
131 * This code handles mapping and unmapping of user data buffers
132 * into DMA'ble space using the IOMMU
135 static struct vfio_dma *vfio_find_dma(struct vfio_iommu *iommu,
136 dma_addr_t start, size_t size)
138 struct rb_node *node = iommu->dma_list.rb_node;
141 struct vfio_dma *dma = rb_entry(node, struct vfio_dma, node);
143 if (start + size <= dma->iova)
144 node = node->rb_left;
145 else if (start >= dma->iova + dma->size)
146 node = node->rb_right;
154 static void vfio_link_dma(struct vfio_iommu *iommu, struct vfio_dma *new)
156 struct rb_node **link = &iommu->dma_list.rb_node, *parent = NULL;
157 struct vfio_dma *dma;
161 dma = rb_entry(parent, struct vfio_dma, node);
163 if (new->iova + new->size <= dma->iova)
164 link = &(*link)->rb_left;
166 link = &(*link)->rb_right;
169 rb_link_node(&new->node, parent, link);
170 rb_insert_color(&new->node, &iommu->dma_list);
173 static void vfio_unlink_dma(struct vfio_iommu *iommu, struct vfio_dma *old)
175 rb_erase(&old->node, &iommu->dma_list);
179 * Helper Functions for host iova-pfn list
181 static struct vfio_pfn *vfio_find_vpfn(struct vfio_dma *dma, dma_addr_t iova)
183 struct vfio_pfn *vpfn;
184 struct rb_node *node = dma->pfn_list.rb_node;
187 vpfn = rb_entry(node, struct vfio_pfn, node);
189 if (iova < vpfn->iova)
190 node = node->rb_left;
191 else if (iova > vpfn->iova)
192 node = node->rb_right;
199 static void vfio_link_pfn(struct vfio_dma *dma,
200 struct vfio_pfn *new)
202 struct rb_node **link, *parent = NULL;
203 struct vfio_pfn *vpfn;
205 link = &dma->pfn_list.rb_node;
208 vpfn = rb_entry(parent, struct vfio_pfn, node);
210 if (new->iova < vpfn->iova)
211 link = &(*link)->rb_left;
213 link = &(*link)->rb_right;
216 rb_link_node(&new->node, parent, link);
217 rb_insert_color(&new->node, &dma->pfn_list);
220 static void vfio_unlink_pfn(struct vfio_dma *dma, struct vfio_pfn *old)
222 rb_erase(&old->node, &dma->pfn_list);
225 static int vfio_add_to_pfn_list(struct vfio_dma *dma, dma_addr_t iova,
228 struct vfio_pfn *vpfn;
230 vpfn = kzalloc(sizeof(*vpfn), GFP_KERNEL);
236 atomic_set(&vpfn->ref_count, 1);
237 vfio_link_pfn(dma, vpfn);
241 static void vfio_remove_from_pfn_list(struct vfio_dma *dma,
242 struct vfio_pfn *vpfn)
244 vfio_unlink_pfn(dma, vpfn);
248 static struct vfio_pfn *vfio_iova_get_vfio_pfn(struct vfio_dma *dma,
251 struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
254 atomic_inc(&vpfn->ref_count);
258 static int vfio_iova_put_vfio_pfn(struct vfio_dma *dma, struct vfio_pfn *vpfn)
262 if (atomic_dec_and_test(&vpfn->ref_count)) {
263 ret = put_pfn(vpfn->pfn, dma->prot);
264 vfio_remove_from_pfn_list(dma, vpfn);
269 static int vfio_lock_acct(struct vfio_dma *dma, long npage, bool async)
271 struct mm_struct *mm;
277 mm = async ? get_task_mm(dma->task) : dma->task->mm;
279 return -ESRCH; /* process exited */
281 ret = down_write_killable(&mm->mmap_sem);
283 ret = __account_locked_vm(mm, abs(npage), npage > 0, dma->task,
285 up_write(&mm->mmap_sem);
295 * Some mappings aren't backed by a struct page, for example an mmap'd
296 * MMIO range for our own or another device. These use a different
297 * pfn conversion and shouldn't be tracked as locked pages.
298 * For compound pages, any driver that sets the reserved bit in head
299 * page needs to set the reserved bit in all subpages to be safe.
301 static bool is_invalid_reserved_pfn(unsigned long pfn)
304 return PageReserved(pfn_to_page(pfn));
309 static int put_pfn(unsigned long pfn, int prot)
311 if (!is_invalid_reserved_pfn(pfn)) {
312 struct page *page = pfn_to_page(pfn);
314 unpin_user_pages_dirty_lock(&page, 1, prot & IOMMU_WRITE);
320 static int vaddr_get_pfn(struct mm_struct *mm, unsigned long vaddr,
321 int prot, unsigned long *pfn)
323 struct page *page[1];
324 struct vm_area_struct *vma;
325 unsigned int flags = 0;
328 if (prot & IOMMU_WRITE)
331 down_read(&mm->mmap_sem);
332 ret = pin_user_pages_remote(NULL, mm, vaddr, 1, flags | FOLL_LONGTERM,
335 *pfn = page_to_pfn(page[0]);
340 vaddr = untagged_addr(vaddr);
342 vma = find_vma_intersection(mm, vaddr, vaddr + 1);
344 if (vma && vma->vm_flags & VM_PFNMAP) {
345 *pfn = ((vaddr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
346 if (is_invalid_reserved_pfn(*pfn))
350 up_read(&mm->mmap_sem);
355 * Attempt to pin pages. We really don't want to track all the pfns and
356 * the iommu can only map chunks of consecutive pfns anyway, so get the
357 * first page and all consecutive pages with the same locking.
359 static long vfio_pin_pages_remote(struct vfio_dma *dma, unsigned long vaddr,
360 long npage, unsigned long *pfn_base,
363 unsigned long pfn = 0;
364 long ret, pinned = 0, lock_acct = 0;
366 dma_addr_t iova = vaddr - dma->vaddr + dma->iova;
368 /* This code path is only user initiated */
372 ret = vaddr_get_pfn(current->mm, vaddr, dma->prot, pfn_base);
377 rsvd = is_invalid_reserved_pfn(*pfn_base);
380 * Reserved pages aren't counted against the user, externally pinned
381 * pages are already counted against the user.
383 if (!rsvd && !vfio_find_vpfn(dma, iova)) {
384 if (!dma->lock_cap && current->mm->locked_vm + 1 > limit) {
385 put_pfn(*pfn_base, dma->prot);
386 pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n", __func__,
387 limit << PAGE_SHIFT);
393 if (unlikely(disable_hugepages))
396 /* Lock all the consecutive pages from pfn_base */
397 for (vaddr += PAGE_SIZE, iova += PAGE_SIZE; pinned < npage;
398 pinned++, vaddr += PAGE_SIZE, iova += PAGE_SIZE) {
399 ret = vaddr_get_pfn(current->mm, vaddr, dma->prot, &pfn);
403 if (pfn != *pfn_base + pinned ||
404 rsvd != is_invalid_reserved_pfn(pfn)) {
405 put_pfn(pfn, dma->prot);
409 if (!rsvd && !vfio_find_vpfn(dma, iova)) {
410 if (!dma->lock_cap &&
411 current->mm->locked_vm + lock_acct + 1 > limit) {
412 put_pfn(pfn, dma->prot);
413 pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n",
414 __func__, limit << PAGE_SHIFT);
423 ret = vfio_lock_acct(dma, lock_acct, false);
428 for (pfn = *pfn_base ; pinned ; pfn++, pinned--)
429 put_pfn(pfn, dma->prot);
438 static long vfio_unpin_pages_remote(struct vfio_dma *dma, dma_addr_t iova,
439 unsigned long pfn, long npage,
442 long unlocked = 0, locked = 0;
445 for (i = 0; i < npage; i++, iova += PAGE_SIZE) {
446 if (put_pfn(pfn++, dma->prot)) {
448 if (vfio_find_vpfn(dma, iova))
454 vfio_lock_acct(dma, locked - unlocked, true);
459 static int vfio_pin_page_external(struct vfio_dma *dma, unsigned long vaddr,
460 unsigned long *pfn_base, bool do_accounting)
462 struct mm_struct *mm;
465 mm = get_task_mm(dma->task);
469 ret = vaddr_get_pfn(mm, vaddr, dma->prot, pfn_base);
470 if (!ret && do_accounting && !is_invalid_reserved_pfn(*pfn_base)) {
471 ret = vfio_lock_acct(dma, 1, true);
473 put_pfn(*pfn_base, dma->prot);
475 pr_warn("%s: Task %s (%d) RLIMIT_MEMLOCK "
476 "(%ld) exceeded\n", __func__,
477 dma->task->comm, task_pid_nr(dma->task),
478 task_rlimit(dma->task, RLIMIT_MEMLOCK));
486 static int vfio_unpin_page_external(struct vfio_dma *dma, dma_addr_t iova,
490 struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
495 unlocked = vfio_iova_put_vfio_pfn(dma, vpfn);
498 vfio_lock_acct(dma, -unlocked, true);
503 static int vfio_iommu_type1_pin_pages(void *iommu_data,
504 unsigned long *user_pfn,
506 unsigned long *phys_pfn)
508 struct vfio_iommu *iommu = iommu_data;
510 unsigned long remote_vaddr;
511 struct vfio_dma *dma;
514 if (!iommu || !user_pfn || !phys_pfn)
517 /* Supported for v2 version only */
521 mutex_lock(&iommu->lock);
523 /* Fail if notifier list is empty */
524 if (!iommu->notifier.head) {
530 * If iommu capable domain exist in the container then all pages are
531 * already pinned and accounted. Accouting should be done if there is no
532 * iommu capable domain in the container.
534 do_accounting = !IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu);
536 for (i = 0; i < npage; i++) {
538 struct vfio_pfn *vpfn;
540 iova = user_pfn[i] << PAGE_SHIFT;
541 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
547 if ((dma->prot & prot) != prot) {
552 vpfn = vfio_iova_get_vfio_pfn(dma, iova);
554 phys_pfn[i] = vpfn->pfn;
558 remote_vaddr = dma->vaddr + iova - dma->iova;
559 ret = vfio_pin_page_external(dma, remote_vaddr, &phys_pfn[i],
564 ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
566 vfio_unpin_page_external(dma, iova, do_accounting);
576 for (j = 0; j < i; j++) {
579 iova = user_pfn[j] << PAGE_SHIFT;
580 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
581 vfio_unpin_page_external(dma, iova, do_accounting);
585 mutex_unlock(&iommu->lock);
589 static int vfio_iommu_type1_unpin_pages(void *iommu_data,
590 unsigned long *user_pfn,
593 struct vfio_iommu *iommu = iommu_data;
597 if (!iommu || !user_pfn)
600 /* Supported for v2 version only */
604 mutex_lock(&iommu->lock);
606 do_accounting = !IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu);
607 for (i = 0; i < npage; i++) {
608 struct vfio_dma *dma;
611 iova = user_pfn[i] << PAGE_SHIFT;
612 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
615 vfio_unpin_page_external(dma, iova, do_accounting);
619 mutex_unlock(&iommu->lock);
620 return i > npage ? npage : (i > 0 ? i : -EINVAL);
623 static long vfio_sync_unpin(struct vfio_dma *dma, struct vfio_domain *domain,
624 struct list_head *regions,
625 struct iommu_iotlb_gather *iotlb_gather)
628 struct vfio_regions *entry, *next;
630 iommu_tlb_sync(domain->domain, iotlb_gather);
632 list_for_each_entry_safe(entry, next, regions, list) {
633 unlocked += vfio_unpin_pages_remote(dma,
635 entry->phys >> PAGE_SHIFT,
636 entry->len >> PAGE_SHIFT,
638 list_del(&entry->list);
648 * Generally, VFIO needs to unpin remote pages after each IOTLB flush.
649 * Therefore, when using IOTLB flush sync interface, VFIO need to keep track
650 * of these regions (currently using a list).
652 * This value specifies maximum number of regions for each IOTLB flush sync.
654 #define VFIO_IOMMU_TLB_SYNC_MAX 512
656 static size_t unmap_unpin_fast(struct vfio_domain *domain,
657 struct vfio_dma *dma, dma_addr_t *iova,
658 size_t len, phys_addr_t phys, long *unlocked,
659 struct list_head *unmapped_list,
661 struct iommu_iotlb_gather *iotlb_gather)
664 struct vfio_regions *entry = kzalloc(sizeof(*entry), GFP_KERNEL);
667 unmapped = iommu_unmap_fast(domain->domain, *iova, len,
675 entry->len = unmapped;
676 list_add_tail(&entry->list, unmapped_list);
684 * Sync if the number of fast-unmap regions hits the limit
685 * or in case of errors.
687 if (*unmapped_cnt >= VFIO_IOMMU_TLB_SYNC_MAX || !unmapped) {
688 *unlocked += vfio_sync_unpin(dma, domain, unmapped_list,
696 static size_t unmap_unpin_slow(struct vfio_domain *domain,
697 struct vfio_dma *dma, dma_addr_t *iova,
698 size_t len, phys_addr_t phys,
701 size_t unmapped = iommu_unmap(domain->domain, *iova, len);
704 *unlocked += vfio_unpin_pages_remote(dma, *iova,
706 unmapped >> PAGE_SHIFT,
714 static long vfio_unmap_unpin(struct vfio_iommu *iommu, struct vfio_dma *dma,
717 dma_addr_t iova = dma->iova, end = dma->iova + dma->size;
718 struct vfio_domain *domain, *d;
719 LIST_HEAD(unmapped_region_list);
720 struct iommu_iotlb_gather iotlb_gather;
721 int unmapped_region_cnt = 0;
727 if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
731 * We use the IOMMU to track the physical addresses, otherwise we'd
732 * need a much more complicated tracking system. Unfortunately that
733 * means we need to use one of the iommu domains to figure out the
734 * pfns to unpin. The rest need to be unmapped in advance so we have
735 * no iommu translations remaining when the pages are unpinned.
737 domain = d = list_first_entry(&iommu->domain_list,
738 struct vfio_domain, next);
740 list_for_each_entry_continue(d, &iommu->domain_list, next) {
741 iommu_unmap(d->domain, dma->iova, dma->size);
745 iommu_iotlb_gather_init(&iotlb_gather);
747 size_t unmapped, len;
748 phys_addr_t phys, next;
750 phys = iommu_iova_to_phys(domain->domain, iova);
751 if (WARN_ON(!phys)) {
757 * To optimize for fewer iommu_unmap() calls, each of which
758 * may require hardware cache flushing, try to find the
759 * largest contiguous physical memory chunk to unmap.
761 for (len = PAGE_SIZE;
762 !domain->fgsp && iova + len < end; len += PAGE_SIZE) {
763 next = iommu_iova_to_phys(domain->domain, iova + len);
764 if (next != phys + len)
769 * First, try to use fast unmap/unpin. In case of failure,
770 * switch to slow unmap/unpin path.
772 unmapped = unmap_unpin_fast(domain, dma, &iova, len, phys,
773 &unlocked, &unmapped_region_list,
774 &unmapped_region_cnt,
777 unmapped = unmap_unpin_slow(domain, dma, &iova, len,
779 if (WARN_ON(!unmapped))
784 dma->iommu_mapped = false;
786 if (unmapped_region_cnt) {
787 unlocked += vfio_sync_unpin(dma, domain, &unmapped_region_list,
792 vfio_lock_acct(dma, -unlocked, true);
798 static void vfio_remove_dma(struct vfio_iommu *iommu, struct vfio_dma *dma)
800 vfio_unmap_unpin(iommu, dma, true);
801 vfio_unlink_dma(iommu, dma);
802 put_task_struct(dma->task);
807 static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
809 struct vfio_domain *domain;
810 unsigned long bitmap = ULONG_MAX;
812 mutex_lock(&iommu->lock);
813 list_for_each_entry(domain, &iommu->domain_list, next)
814 bitmap &= domain->domain->pgsize_bitmap;
815 mutex_unlock(&iommu->lock);
818 * In case the IOMMU supports page sizes smaller than PAGE_SIZE
819 * we pretend PAGE_SIZE is supported and hide sub-PAGE_SIZE sizes.
820 * That way the user will be able to map/unmap buffers whose size/
821 * start address is aligned with PAGE_SIZE. Pinning code uses that
822 * granularity while iommu driver can use the sub-PAGE_SIZE size
825 if (bitmap & ~PAGE_MASK) {
833 static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
834 struct vfio_iommu_type1_dma_unmap *unmap)
837 struct vfio_dma *dma, *dma_last = NULL;
839 int ret = 0, retries = 0;
841 mask = ((uint64_t)1 << __ffs(vfio_pgsize_bitmap(iommu))) - 1;
843 if (unmap->iova & mask)
845 if (!unmap->size || unmap->size & mask)
847 if (unmap->iova + unmap->size - 1 < unmap->iova ||
848 unmap->size > SIZE_MAX)
851 WARN_ON(mask & PAGE_MASK);
853 mutex_lock(&iommu->lock);
856 * vfio-iommu-type1 (v1) - User mappings were coalesced together to
857 * avoid tracking individual mappings. This means that the granularity
858 * of the original mapping was lost and the user was allowed to attempt
859 * to unmap any range. Depending on the contiguousness of physical
860 * memory and page sizes supported by the IOMMU, arbitrary unmaps may
861 * or may not have worked. We only guaranteed unmap granularity
862 * matching the original mapping; even though it was untracked here,
863 * the original mappings are reflected in IOMMU mappings. This
864 * resulted in a couple unusual behaviors. First, if a range is not
865 * able to be unmapped, ex. a set of 4k pages that was mapped as a
866 * 2M hugepage into the IOMMU, the unmap ioctl returns success but with
867 * a zero sized unmap. Also, if an unmap request overlaps the first
868 * address of a hugepage, the IOMMU will unmap the entire hugepage.
869 * This also returns success and the returned unmap size reflects the
870 * actual size unmapped.
872 * We attempt to maintain compatibility with this "v1" interface, but
873 * we take control out of the hands of the IOMMU. Therefore, an unmap
874 * request offset from the beginning of the original mapping will
875 * return success with zero sized unmap. And an unmap request covering
876 * the first iova of mapping will unmap the entire range.
878 * The v2 version of this interface intends to be more deterministic.
879 * Unmap requests must fully cover previous mappings. Multiple
880 * mappings may still be unmaped by specifying large ranges, but there
881 * must not be any previous mappings bisected by the range. An error
882 * will be returned if these conditions are not met. The v2 interface
883 * will only return success and a size of zero if there were no
884 * mappings within the range.
887 dma = vfio_find_dma(iommu, unmap->iova, 1);
888 if (dma && dma->iova != unmap->iova) {
892 dma = vfio_find_dma(iommu, unmap->iova + unmap->size - 1, 0);
893 if (dma && dma->iova + dma->size != unmap->iova + unmap->size) {
899 while ((dma = vfio_find_dma(iommu, unmap->iova, unmap->size))) {
900 if (!iommu->v2 && unmap->iova > dma->iova)
903 * Task with same address space who mapped this iova range is
904 * allowed to unmap the iova range.
906 if (dma->task->mm != current->mm)
909 if (!RB_EMPTY_ROOT(&dma->pfn_list)) {
910 struct vfio_iommu_type1_dma_unmap nb_unmap;
912 if (dma_last == dma) {
913 BUG_ON(++retries > 10);
919 nb_unmap.iova = dma->iova;
920 nb_unmap.size = dma->size;
923 * Notify anyone (mdev vendor drivers) to invalidate and
924 * unmap iovas within the range we're about to unmap.
925 * Vendor drivers MUST unpin pages in response to an
928 mutex_unlock(&iommu->lock);
929 blocking_notifier_call_chain(&iommu->notifier,
930 VFIO_IOMMU_NOTIFY_DMA_UNMAP,
934 unmapped += dma->size;
935 vfio_remove_dma(iommu, dma);
939 mutex_unlock(&iommu->lock);
941 /* Report how much was unmapped */
942 unmap->size = unmapped;
947 static int vfio_iommu_map(struct vfio_iommu *iommu, dma_addr_t iova,
948 unsigned long pfn, long npage, int prot)
950 struct vfio_domain *d;
953 list_for_each_entry(d, &iommu->domain_list, next) {
954 ret = iommu_map(d->domain, iova, (phys_addr_t)pfn << PAGE_SHIFT,
955 npage << PAGE_SHIFT, prot | d->prot);
965 list_for_each_entry_continue_reverse(d, &iommu->domain_list, next)
966 iommu_unmap(d->domain, iova, npage << PAGE_SHIFT);
971 static int vfio_pin_map_dma(struct vfio_iommu *iommu, struct vfio_dma *dma,
974 dma_addr_t iova = dma->iova;
975 unsigned long vaddr = dma->vaddr;
976 size_t size = map_size;
978 unsigned long pfn, limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
982 /* Pin a contiguous chunk of memory */
983 npage = vfio_pin_pages_remote(dma, vaddr + dma->size,
984 size >> PAGE_SHIFT, &pfn, limit);
992 ret = vfio_iommu_map(iommu, iova + dma->size, pfn, npage,
995 vfio_unpin_pages_remote(dma, iova + dma->size, pfn,
1000 size -= npage << PAGE_SHIFT;
1001 dma->size += npage << PAGE_SHIFT;
1004 dma->iommu_mapped = true;
1007 vfio_remove_dma(iommu, dma);
1013 * Check dma map request is within a valid iova range
1015 static bool vfio_iommu_iova_dma_valid(struct vfio_iommu *iommu,
1016 dma_addr_t start, dma_addr_t end)
1018 struct list_head *iova = &iommu->iova_list;
1019 struct vfio_iova *node;
1021 list_for_each_entry(node, iova, list) {
1022 if (start >= node->start && end <= node->end)
1027 * Check for list_empty() as well since a container with
1028 * a single mdev device will have an empty list.
1030 return list_empty(iova);
1033 static int vfio_dma_do_map(struct vfio_iommu *iommu,
1034 struct vfio_iommu_type1_dma_map *map)
1036 dma_addr_t iova = map->iova;
1037 unsigned long vaddr = map->vaddr;
1038 size_t size = map->size;
1039 int ret = 0, prot = 0;
1041 struct vfio_dma *dma;
1043 /* Verify that none of our __u64 fields overflow */
1044 if (map->size != size || map->vaddr != vaddr || map->iova != iova)
1047 mask = ((uint64_t)1 << __ffs(vfio_pgsize_bitmap(iommu))) - 1;
1049 WARN_ON(mask & PAGE_MASK);
1051 /* READ/WRITE from device perspective */
1052 if (map->flags & VFIO_DMA_MAP_FLAG_WRITE)
1053 prot |= IOMMU_WRITE;
1054 if (map->flags & VFIO_DMA_MAP_FLAG_READ)
1057 if (!prot || !size || (size | iova | vaddr) & mask)
1060 /* Don't allow IOVA or virtual address wrap */
1061 if (iova + size - 1 < iova || vaddr + size - 1 < vaddr)
1064 mutex_lock(&iommu->lock);
1066 if (vfio_find_dma(iommu, iova, size)) {
1071 if (!iommu->dma_avail) {
1076 if (!vfio_iommu_iova_dma_valid(iommu, iova, iova + size - 1)) {
1081 dma = kzalloc(sizeof(*dma), GFP_KERNEL);
1093 * We need to be able to both add to a task's locked memory and test
1094 * against the locked memory limit and we need to be able to do both
1095 * outside of this call path as pinning can be asynchronous via the
1096 * external interfaces for mdev devices. RLIMIT_MEMLOCK requires a
1097 * task_struct and VM locked pages requires an mm_struct, however
1098 * holding an indefinite mm reference is not recommended, therefore we
1099 * only hold a reference to a task. We could hold a reference to
1100 * current, however QEMU uses this call path through vCPU threads,
1101 * which can be killed resulting in a NULL mm and failure in the unmap
1102 * path when called via a different thread. Avoid this problem by
1103 * using the group_leader as threads within the same group require
1104 * both CLONE_THREAD and CLONE_VM and will therefore use the same
1107 * Previously we also used the task for testing CAP_IPC_LOCK at the
1108 * time of pinning and accounting, however has_capability() makes use
1109 * of real_cred, a copy-on-write field, so we can't guarantee that it
1110 * matches group_leader, or in fact that it might not change by the
1111 * time it's evaluated. If a process were to call MAP_DMA with
1112 * CAP_IPC_LOCK but later drop it, it doesn't make sense that they
1113 * possibly see different results for an iommu_mapped vfio_dma vs
1114 * externally mapped. Therefore track CAP_IPC_LOCK in vfio_dma at the
1115 * time of calling MAP_DMA.
1117 get_task_struct(current->group_leader);
1118 dma->task = current->group_leader;
1119 dma->lock_cap = capable(CAP_IPC_LOCK);
1121 dma->pfn_list = RB_ROOT;
1123 /* Insert zero-sized and grow as we map chunks of it */
1124 vfio_link_dma(iommu, dma);
1126 /* Don't pin and map if container doesn't contain IOMMU capable domain*/
1127 if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
1130 ret = vfio_pin_map_dma(iommu, dma, size);
1133 mutex_unlock(&iommu->lock);
1137 static int vfio_bus_type(struct device *dev, void *data)
1139 struct bus_type **bus = data;
1141 if (*bus && *bus != dev->bus)
1149 static int vfio_iommu_replay(struct vfio_iommu *iommu,
1150 struct vfio_domain *domain)
1152 struct vfio_domain *d;
1154 unsigned long limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1157 /* Arbitrarily pick the first domain in the list for lookups */
1158 d = list_first_entry(&iommu->domain_list, struct vfio_domain, next);
1159 n = rb_first(&iommu->dma_list);
1161 for (; n; n = rb_next(n)) {
1162 struct vfio_dma *dma;
1165 dma = rb_entry(n, struct vfio_dma, node);
1168 while (iova < dma->iova + dma->size) {
1172 if (dma->iommu_mapped) {
1176 phys = iommu_iova_to_phys(d->domain, iova);
1178 if (WARN_ON(!phys)) {
1186 while (i < dma->iova + dma->size &&
1187 p == iommu_iova_to_phys(d->domain, i)) {
1194 unsigned long vaddr = dma->vaddr +
1196 size_t n = dma->iova + dma->size - iova;
1199 npage = vfio_pin_pages_remote(dma, vaddr,
1208 phys = pfn << PAGE_SHIFT;
1209 size = npage << PAGE_SHIFT;
1212 ret = iommu_map(domain->domain, iova, phys,
1213 size, dma->prot | domain->prot);
1219 dma->iommu_mapped = true;
1225 * We change our unmap behavior slightly depending on whether the IOMMU
1226 * supports fine-grained superpages. IOMMUs like AMD-Vi will use a superpage
1227 * for practically any contiguous power-of-two mapping we give it. This means
1228 * we don't need to look for contiguous chunks ourselves to make unmapping
1229 * more efficient. On IOMMUs with coarse-grained super pages, like Intel VT-d
1230 * with discrete 2M/1G/512G/1T superpages, identifying contiguous chunks
1231 * significantly boosts non-hugetlbfs mappings and doesn't seem to hurt when
1232 * hugetlbfs is in use.
1234 static void vfio_test_domain_fgsp(struct vfio_domain *domain)
1237 int ret, order = get_order(PAGE_SIZE * 2);
1239 pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, order);
1243 ret = iommu_map(domain->domain, 0, page_to_phys(pages), PAGE_SIZE * 2,
1244 IOMMU_READ | IOMMU_WRITE | domain->prot);
1246 size_t unmapped = iommu_unmap(domain->domain, 0, PAGE_SIZE);
1248 if (unmapped == PAGE_SIZE)
1249 iommu_unmap(domain->domain, PAGE_SIZE, PAGE_SIZE);
1251 domain->fgsp = true;
1254 __free_pages(pages, order);
1257 static struct vfio_group *find_iommu_group(struct vfio_domain *domain,
1258 struct iommu_group *iommu_group)
1260 struct vfio_group *g;
1262 list_for_each_entry(g, &domain->group_list, next) {
1263 if (g->iommu_group == iommu_group)
1270 static bool vfio_iommu_has_sw_msi(struct list_head *group_resv_regions,
1273 struct iommu_resv_region *region;
1276 list_for_each_entry(region, group_resv_regions, list) {
1278 * The presence of any 'real' MSI regions should take
1279 * precedence over the software-managed one if the
1280 * IOMMU driver happens to advertise both types.
1282 if (region->type == IOMMU_RESV_MSI) {
1287 if (region->type == IOMMU_RESV_SW_MSI) {
1288 *base = region->start;
1296 static struct device *vfio_mdev_get_iommu_device(struct device *dev)
1298 struct device *(*fn)(struct device *dev);
1299 struct device *iommu_device;
1301 fn = symbol_get(mdev_get_iommu_device);
1303 iommu_device = fn(dev);
1304 symbol_put(mdev_get_iommu_device);
1306 return iommu_device;
1312 static int vfio_mdev_attach_domain(struct device *dev, void *data)
1314 struct iommu_domain *domain = data;
1315 struct device *iommu_device;
1317 iommu_device = vfio_mdev_get_iommu_device(dev);
1319 if (iommu_dev_feature_enabled(iommu_device, IOMMU_DEV_FEAT_AUX))
1320 return iommu_aux_attach_device(domain, iommu_device);
1322 return iommu_attach_device(domain, iommu_device);
1328 static int vfio_mdev_detach_domain(struct device *dev, void *data)
1330 struct iommu_domain *domain = data;
1331 struct device *iommu_device;
1333 iommu_device = vfio_mdev_get_iommu_device(dev);
1335 if (iommu_dev_feature_enabled(iommu_device, IOMMU_DEV_FEAT_AUX))
1336 iommu_aux_detach_device(domain, iommu_device);
1338 iommu_detach_device(domain, iommu_device);
1344 static int vfio_iommu_attach_group(struct vfio_domain *domain,
1345 struct vfio_group *group)
1347 if (group->mdev_group)
1348 return iommu_group_for_each_dev(group->iommu_group,
1350 vfio_mdev_attach_domain);
1352 return iommu_attach_group(domain->domain, group->iommu_group);
1355 static void vfio_iommu_detach_group(struct vfio_domain *domain,
1356 struct vfio_group *group)
1358 if (group->mdev_group)
1359 iommu_group_for_each_dev(group->iommu_group, domain->domain,
1360 vfio_mdev_detach_domain);
1362 iommu_detach_group(domain->domain, group->iommu_group);
1365 static bool vfio_bus_is_mdev(struct bus_type *bus)
1367 struct bus_type *mdev_bus;
1370 mdev_bus = symbol_get(mdev_bus_type);
1372 ret = (bus == mdev_bus);
1373 symbol_put(mdev_bus_type);
1379 static int vfio_mdev_iommu_device(struct device *dev, void *data)
1381 struct device **old = data, *new;
1383 new = vfio_mdev_get_iommu_device(dev);
1384 if (!new || (*old && *old != new))
1393 * This is a helper function to insert an address range to iova list.
1394 * The list is initially created with a single entry corresponding to
1395 * the IOMMU domain geometry to which the device group is attached.
1396 * The list aperture gets modified when a new domain is added to the
1397 * container if the new aperture doesn't conflict with the current one
1398 * or with any existing dma mappings. The list is also modified to
1399 * exclude any reserved regions associated with the device group.
1401 static int vfio_iommu_iova_insert(struct list_head *head,
1402 dma_addr_t start, dma_addr_t end)
1404 struct vfio_iova *region;
1406 region = kmalloc(sizeof(*region), GFP_KERNEL);
1410 INIT_LIST_HEAD(®ion->list);
1411 region->start = start;
1414 list_add_tail(®ion->list, head);
1419 * Check the new iommu aperture conflicts with existing aper or with any
1420 * existing dma mappings.
1422 static bool vfio_iommu_aper_conflict(struct vfio_iommu *iommu,
1423 dma_addr_t start, dma_addr_t end)
1425 struct vfio_iova *first, *last;
1426 struct list_head *iova = &iommu->iova_list;
1428 if (list_empty(iova))
1431 /* Disjoint sets, return conflict */
1432 first = list_first_entry(iova, struct vfio_iova, list);
1433 last = list_last_entry(iova, struct vfio_iova, list);
1434 if (start > last->end || end < first->start)
1437 /* Check for any existing dma mappings below the new start */
1438 if (start > first->start) {
1439 if (vfio_find_dma(iommu, first->start, start - first->start))
1443 /* Check for any existing dma mappings beyond the new end */
1444 if (end < last->end) {
1445 if (vfio_find_dma(iommu, end + 1, last->end - end))
1453 * Resize iommu iova aperture window. This is called only if the new
1454 * aperture has no conflict with existing aperture and dma mappings.
1456 static int vfio_iommu_aper_resize(struct list_head *iova,
1457 dma_addr_t start, dma_addr_t end)
1459 struct vfio_iova *node, *next;
1461 if (list_empty(iova))
1462 return vfio_iommu_iova_insert(iova, start, end);
1464 /* Adjust iova list start */
1465 list_for_each_entry_safe(node, next, iova, list) {
1466 if (start < node->start)
1468 if (start >= node->start && start < node->end) {
1469 node->start = start;
1472 /* Delete nodes before new start */
1473 list_del(&node->list);
1477 /* Adjust iova list end */
1478 list_for_each_entry_safe(node, next, iova, list) {
1479 if (end > node->end)
1481 if (end > node->start && end <= node->end) {
1485 /* Delete nodes after new end */
1486 list_del(&node->list);
1494 * Check reserved region conflicts with existing dma mappings
1496 static bool vfio_iommu_resv_conflict(struct vfio_iommu *iommu,
1497 struct list_head *resv_regions)
1499 struct iommu_resv_region *region;
1501 /* Check for conflict with existing dma mappings */
1502 list_for_each_entry(region, resv_regions, list) {
1503 if (region->type == IOMMU_RESV_DIRECT_RELAXABLE)
1506 if (vfio_find_dma(iommu, region->start, region->length))
1514 * Check iova region overlap with reserved regions and
1515 * exclude them from the iommu iova range
1517 static int vfio_iommu_resv_exclude(struct list_head *iova,
1518 struct list_head *resv_regions)
1520 struct iommu_resv_region *resv;
1521 struct vfio_iova *n, *next;
1523 list_for_each_entry(resv, resv_regions, list) {
1524 phys_addr_t start, end;
1526 if (resv->type == IOMMU_RESV_DIRECT_RELAXABLE)
1529 start = resv->start;
1530 end = resv->start + resv->length - 1;
1532 list_for_each_entry_safe(n, next, iova, list) {
1536 if (start > n->end || end < n->start)
1539 * Insert a new node if current node overlaps with the
1540 * reserve region to exlude that from valid iova range.
1541 * Note that, new node is inserted before the current
1542 * node and finally the current node is deleted keeping
1543 * the list updated and sorted.
1545 if (start > n->start)
1546 ret = vfio_iommu_iova_insert(&n->list, n->start,
1548 if (!ret && end < n->end)
1549 ret = vfio_iommu_iova_insert(&n->list, end + 1,
1559 if (list_empty(iova))
1565 static void vfio_iommu_resv_free(struct list_head *resv_regions)
1567 struct iommu_resv_region *n, *next;
1569 list_for_each_entry_safe(n, next, resv_regions, list) {
1575 static void vfio_iommu_iova_free(struct list_head *iova)
1577 struct vfio_iova *n, *next;
1579 list_for_each_entry_safe(n, next, iova, list) {
1585 static int vfio_iommu_iova_get_copy(struct vfio_iommu *iommu,
1586 struct list_head *iova_copy)
1588 struct list_head *iova = &iommu->iova_list;
1589 struct vfio_iova *n;
1592 list_for_each_entry(n, iova, list) {
1593 ret = vfio_iommu_iova_insert(iova_copy, n->start, n->end);
1601 vfio_iommu_iova_free(iova_copy);
1605 static void vfio_iommu_iova_insert_copy(struct vfio_iommu *iommu,
1606 struct list_head *iova_copy)
1608 struct list_head *iova = &iommu->iova_list;
1610 vfio_iommu_iova_free(iova);
1612 list_splice_tail(iova_copy, iova);
1614 static int vfio_iommu_type1_attach_group(void *iommu_data,
1615 struct iommu_group *iommu_group)
1617 struct vfio_iommu *iommu = iommu_data;
1618 struct vfio_group *group;
1619 struct vfio_domain *domain, *d;
1620 struct bus_type *bus = NULL;
1622 bool resv_msi, msi_remap;
1623 phys_addr_t resv_msi_base = 0;
1624 struct iommu_domain_geometry geo;
1625 LIST_HEAD(iova_copy);
1626 LIST_HEAD(group_resv_regions);
1628 mutex_lock(&iommu->lock);
1630 list_for_each_entry(d, &iommu->domain_list, next) {
1631 if (find_iommu_group(d, iommu_group)) {
1632 mutex_unlock(&iommu->lock);
1637 if (iommu->external_domain) {
1638 if (find_iommu_group(iommu->external_domain, iommu_group)) {
1639 mutex_unlock(&iommu->lock);
1644 group = kzalloc(sizeof(*group), GFP_KERNEL);
1645 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
1646 if (!group || !domain) {
1651 group->iommu_group = iommu_group;
1653 /* Determine bus_type in order to allocate a domain */
1654 ret = iommu_group_for_each_dev(iommu_group, &bus, vfio_bus_type);
1658 if (vfio_bus_is_mdev(bus)) {
1659 struct device *iommu_device = NULL;
1661 group->mdev_group = true;
1663 /* Determine the isolation type */
1664 ret = iommu_group_for_each_dev(iommu_group, &iommu_device,
1665 vfio_mdev_iommu_device);
1666 if (ret || !iommu_device) {
1667 if (!iommu->external_domain) {
1668 INIT_LIST_HEAD(&domain->group_list);
1669 iommu->external_domain = domain;
1674 list_add(&group->next,
1675 &iommu->external_domain->group_list);
1676 mutex_unlock(&iommu->lock);
1681 bus = iommu_device->bus;
1684 domain->domain = iommu_domain_alloc(bus);
1685 if (!domain->domain) {
1690 if (iommu->nesting) {
1693 ret = iommu_domain_set_attr(domain->domain, DOMAIN_ATTR_NESTING,
1699 ret = vfio_iommu_attach_group(domain, group);
1703 /* Get aperture info */
1704 iommu_domain_get_attr(domain->domain, DOMAIN_ATTR_GEOMETRY, &geo);
1706 if (vfio_iommu_aper_conflict(iommu, geo.aperture_start,
1707 geo.aperture_end)) {
1712 ret = iommu_get_group_resv_regions(iommu_group, &group_resv_regions);
1716 if (vfio_iommu_resv_conflict(iommu, &group_resv_regions)) {
1722 * We don't want to work on the original iova list as the list
1723 * gets modified and in case of failure we have to retain the
1724 * original list. Get a copy here.
1726 ret = vfio_iommu_iova_get_copy(iommu, &iova_copy);
1730 ret = vfio_iommu_aper_resize(&iova_copy, geo.aperture_start,
1735 ret = vfio_iommu_resv_exclude(&iova_copy, &group_resv_regions);
1739 resv_msi = vfio_iommu_has_sw_msi(&group_resv_regions, &resv_msi_base);
1741 INIT_LIST_HEAD(&domain->group_list);
1742 list_add(&group->next, &domain->group_list);
1744 msi_remap = irq_domain_check_msi_remap() ||
1745 iommu_capable(bus, IOMMU_CAP_INTR_REMAP);
1747 if (!allow_unsafe_interrupts && !msi_remap) {
1748 pr_warn("%s: No interrupt remapping support. Use the module param \"allow_unsafe_interrupts\" to enable VFIO IOMMU support on this platform\n",
1754 if (iommu_capable(bus, IOMMU_CAP_CACHE_COHERENCY))
1755 domain->prot |= IOMMU_CACHE;
1758 * Try to match an existing compatible domain. We don't want to
1759 * preclude an IOMMU driver supporting multiple bus_types and being
1760 * able to include different bus_types in the same IOMMU domain, so
1761 * we test whether the domains use the same iommu_ops rather than
1762 * testing if they're on the same bus_type.
1764 list_for_each_entry(d, &iommu->domain_list, next) {
1765 if (d->domain->ops == domain->domain->ops &&
1766 d->prot == domain->prot) {
1767 vfio_iommu_detach_group(domain, group);
1768 if (!vfio_iommu_attach_group(d, group)) {
1769 list_add(&group->next, &d->group_list);
1770 iommu_domain_free(domain->domain);
1775 ret = vfio_iommu_attach_group(domain, group);
1781 vfio_test_domain_fgsp(domain);
1783 /* replay mappings on new domains */
1784 ret = vfio_iommu_replay(iommu, domain);
1789 ret = iommu_get_msi_cookie(domain->domain, resv_msi_base);
1790 if (ret && ret != -ENODEV)
1794 list_add(&domain->next, &iommu->domain_list);
1796 /* Delete the old one and insert new iova list */
1797 vfio_iommu_iova_insert_copy(iommu, &iova_copy);
1798 mutex_unlock(&iommu->lock);
1799 vfio_iommu_resv_free(&group_resv_regions);
1804 vfio_iommu_detach_group(domain, group);
1806 iommu_domain_free(domain->domain);
1807 vfio_iommu_iova_free(&iova_copy);
1808 vfio_iommu_resv_free(&group_resv_regions);
1812 mutex_unlock(&iommu->lock);
1816 static void vfio_iommu_unmap_unpin_all(struct vfio_iommu *iommu)
1818 struct rb_node *node;
1820 while ((node = rb_first(&iommu->dma_list)))
1821 vfio_remove_dma(iommu, rb_entry(node, struct vfio_dma, node));
1824 static void vfio_iommu_unmap_unpin_reaccount(struct vfio_iommu *iommu)
1826 struct rb_node *n, *p;
1828 n = rb_first(&iommu->dma_list);
1829 for (; n; n = rb_next(n)) {
1830 struct vfio_dma *dma;
1831 long locked = 0, unlocked = 0;
1833 dma = rb_entry(n, struct vfio_dma, node);
1834 unlocked += vfio_unmap_unpin(iommu, dma, false);
1835 p = rb_first(&dma->pfn_list);
1836 for (; p; p = rb_next(p)) {
1837 struct vfio_pfn *vpfn = rb_entry(p, struct vfio_pfn,
1840 if (!is_invalid_reserved_pfn(vpfn->pfn))
1843 vfio_lock_acct(dma, locked - unlocked, true);
1847 static void vfio_sanity_check_pfn_list(struct vfio_iommu *iommu)
1851 n = rb_first(&iommu->dma_list);
1852 for (; n; n = rb_next(n)) {
1853 struct vfio_dma *dma;
1855 dma = rb_entry(n, struct vfio_dma, node);
1857 if (WARN_ON(!RB_EMPTY_ROOT(&dma->pfn_list)))
1860 /* mdev vendor driver must unregister notifier */
1861 WARN_ON(iommu->notifier.head);
1865 * Called when a domain is removed in detach. It is possible that
1866 * the removed domain decided the iova aperture window. Modify the
1867 * iova aperture with the smallest window among existing domains.
1869 static void vfio_iommu_aper_expand(struct vfio_iommu *iommu,
1870 struct list_head *iova_copy)
1872 struct vfio_domain *domain;
1873 struct iommu_domain_geometry geo;
1874 struct vfio_iova *node;
1875 dma_addr_t start = 0;
1876 dma_addr_t end = (dma_addr_t)~0;
1878 if (list_empty(iova_copy))
1881 list_for_each_entry(domain, &iommu->domain_list, next) {
1882 iommu_domain_get_attr(domain->domain, DOMAIN_ATTR_GEOMETRY,
1884 if (geo.aperture_start > start)
1885 start = geo.aperture_start;
1886 if (geo.aperture_end < end)
1887 end = geo.aperture_end;
1890 /* Modify aperture limits. The new aper is either same or bigger */
1891 node = list_first_entry(iova_copy, struct vfio_iova, list);
1892 node->start = start;
1893 node = list_last_entry(iova_copy, struct vfio_iova, list);
1898 * Called when a group is detached. The reserved regions for that
1899 * group can be part of valid iova now. But since reserved regions
1900 * may be duplicated among groups, populate the iova valid regions
1903 static int vfio_iommu_resv_refresh(struct vfio_iommu *iommu,
1904 struct list_head *iova_copy)
1906 struct vfio_domain *d;
1907 struct vfio_group *g;
1908 struct vfio_iova *node;
1909 dma_addr_t start, end;
1910 LIST_HEAD(resv_regions);
1913 if (list_empty(iova_copy))
1916 list_for_each_entry(d, &iommu->domain_list, next) {
1917 list_for_each_entry(g, &d->group_list, next) {
1918 ret = iommu_get_group_resv_regions(g->iommu_group,
1925 node = list_first_entry(iova_copy, struct vfio_iova, list);
1926 start = node->start;
1927 node = list_last_entry(iova_copy, struct vfio_iova, list);
1930 /* purge the iova list and create new one */
1931 vfio_iommu_iova_free(iova_copy);
1933 ret = vfio_iommu_aper_resize(iova_copy, start, end);
1937 /* Exclude current reserved regions from iova ranges */
1938 ret = vfio_iommu_resv_exclude(iova_copy, &resv_regions);
1940 vfio_iommu_resv_free(&resv_regions);
1944 static void vfio_iommu_type1_detach_group(void *iommu_data,
1945 struct iommu_group *iommu_group)
1947 struct vfio_iommu *iommu = iommu_data;
1948 struct vfio_domain *domain;
1949 struct vfio_group *group;
1950 LIST_HEAD(iova_copy);
1952 mutex_lock(&iommu->lock);
1954 if (iommu->external_domain) {
1955 group = find_iommu_group(iommu->external_domain, iommu_group);
1957 list_del(&group->next);
1960 if (list_empty(&iommu->external_domain->group_list)) {
1961 vfio_sanity_check_pfn_list(iommu);
1963 if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
1964 vfio_iommu_unmap_unpin_all(iommu);
1966 kfree(iommu->external_domain);
1967 iommu->external_domain = NULL;
1969 goto detach_group_done;
1974 * Get a copy of iova list. This will be used to update
1975 * and to replace the current one later. Please note that
1976 * we will leave the original list as it is if update fails.
1978 vfio_iommu_iova_get_copy(iommu, &iova_copy);
1980 list_for_each_entry(domain, &iommu->domain_list, next) {
1981 group = find_iommu_group(domain, iommu_group);
1985 vfio_iommu_detach_group(domain, group);
1986 list_del(&group->next);
1989 * Group ownership provides privilege, if the group list is
1990 * empty, the domain goes away. If it's the last domain with
1991 * iommu and external domain doesn't exist, then all the
1992 * mappings go away too. If it's the last domain with iommu and
1993 * external domain exist, update accounting
1995 if (list_empty(&domain->group_list)) {
1996 if (list_is_singular(&iommu->domain_list)) {
1997 if (!iommu->external_domain)
1998 vfio_iommu_unmap_unpin_all(iommu);
2000 vfio_iommu_unmap_unpin_reaccount(iommu);
2002 iommu_domain_free(domain->domain);
2003 list_del(&domain->next);
2005 vfio_iommu_aper_expand(iommu, &iova_copy);
2010 if (!vfio_iommu_resv_refresh(iommu, &iova_copy))
2011 vfio_iommu_iova_insert_copy(iommu, &iova_copy);
2013 vfio_iommu_iova_free(&iova_copy);
2016 mutex_unlock(&iommu->lock);
2019 static void *vfio_iommu_type1_open(unsigned long arg)
2021 struct vfio_iommu *iommu;
2023 iommu = kzalloc(sizeof(*iommu), GFP_KERNEL);
2025 return ERR_PTR(-ENOMEM);
2028 case VFIO_TYPE1_IOMMU:
2030 case VFIO_TYPE1_NESTING_IOMMU:
2031 iommu->nesting = true;
2033 case VFIO_TYPE1v2_IOMMU:
2038 return ERR_PTR(-EINVAL);
2041 INIT_LIST_HEAD(&iommu->domain_list);
2042 INIT_LIST_HEAD(&iommu->iova_list);
2043 iommu->dma_list = RB_ROOT;
2044 iommu->dma_avail = dma_entry_limit;
2045 mutex_init(&iommu->lock);
2046 BLOCKING_INIT_NOTIFIER_HEAD(&iommu->notifier);
2051 static void vfio_release_domain(struct vfio_domain *domain, bool external)
2053 struct vfio_group *group, *group_tmp;
2055 list_for_each_entry_safe(group, group_tmp,
2056 &domain->group_list, next) {
2058 vfio_iommu_detach_group(domain, group);
2059 list_del(&group->next);
2064 iommu_domain_free(domain->domain);
2067 static void vfio_iommu_type1_release(void *iommu_data)
2069 struct vfio_iommu *iommu = iommu_data;
2070 struct vfio_domain *domain, *domain_tmp;
2072 if (iommu->external_domain) {
2073 vfio_release_domain(iommu->external_domain, true);
2074 vfio_sanity_check_pfn_list(iommu);
2075 kfree(iommu->external_domain);
2078 vfio_iommu_unmap_unpin_all(iommu);
2080 list_for_each_entry_safe(domain, domain_tmp,
2081 &iommu->domain_list, next) {
2082 vfio_release_domain(domain, false);
2083 list_del(&domain->next);
2087 vfio_iommu_iova_free(&iommu->iova_list);
2092 static int vfio_domains_have_iommu_cache(struct vfio_iommu *iommu)
2094 struct vfio_domain *domain;
2097 mutex_lock(&iommu->lock);
2098 list_for_each_entry(domain, &iommu->domain_list, next) {
2099 if (!(domain->prot & IOMMU_CACHE)) {
2104 mutex_unlock(&iommu->lock);
2109 static int vfio_iommu_iova_add_cap(struct vfio_info_cap *caps,
2110 struct vfio_iommu_type1_info_cap_iova_range *cap_iovas,
2113 struct vfio_info_cap_header *header;
2114 struct vfio_iommu_type1_info_cap_iova_range *iova_cap;
2116 header = vfio_info_cap_add(caps, size,
2117 VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE, 1);
2119 return PTR_ERR(header);
2121 iova_cap = container_of(header,
2122 struct vfio_iommu_type1_info_cap_iova_range,
2124 iova_cap->nr_iovas = cap_iovas->nr_iovas;
2125 memcpy(iova_cap->iova_ranges, cap_iovas->iova_ranges,
2126 cap_iovas->nr_iovas * sizeof(*cap_iovas->iova_ranges));
2130 static int vfio_iommu_iova_build_caps(struct vfio_iommu *iommu,
2131 struct vfio_info_cap *caps)
2133 struct vfio_iommu_type1_info_cap_iova_range *cap_iovas;
2134 struct vfio_iova *iova;
2136 int iovas = 0, i = 0, ret;
2138 mutex_lock(&iommu->lock);
2140 list_for_each_entry(iova, &iommu->iova_list, list)
2145 * Return 0 as a container with a single mdev device
2146 * will have an empty list
2152 size = sizeof(*cap_iovas) + (iovas * sizeof(*cap_iovas->iova_ranges));
2154 cap_iovas = kzalloc(size, GFP_KERNEL);
2160 cap_iovas->nr_iovas = iovas;
2162 list_for_each_entry(iova, &iommu->iova_list, list) {
2163 cap_iovas->iova_ranges[i].start = iova->start;
2164 cap_iovas->iova_ranges[i].end = iova->end;
2168 ret = vfio_iommu_iova_add_cap(caps, cap_iovas, size);
2172 mutex_unlock(&iommu->lock);
2176 static long vfio_iommu_type1_ioctl(void *iommu_data,
2177 unsigned int cmd, unsigned long arg)
2179 struct vfio_iommu *iommu = iommu_data;
2180 unsigned long minsz;
2182 if (cmd == VFIO_CHECK_EXTENSION) {
2184 case VFIO_TYPE1_IOMMU:
2185 case VFIO_TYPE1v2_IOMMU:
2186 case VFIO_TYPE1_NESTING_IOMMU:
2188 case VFIO_DMA_CC_IOMMU:
2191 return vfio_domains_have_iommu_cache(iommu);
2195 } else if (cmd == VFIO_IOMMU_GET_INFO) {
2196 struct vfio_iommu_type1_info info;
2197 struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
2198 unsigned long capsz;
2201 minsz = offsetofend(struct vfio_iommu_type1_info, iova_pgsizes);
2203 /* For backward compatibility, cannot require this */
2204 capsz = offsetofend(struct vfio_iommu_type1_info, cap_offset);
2206 if (copy_from_user(&info, (void __user *)arg, minsz))
2209 if (info.argsz < minsz)
2212 if (info.argsz >= capsz) {
2214 info.cap_offset = 0; /* output, no-recopy necessary */
2217 info.flags = VFIO_IOMMU_INFO_PGSIZES;
2219 info.iova_pgsizes = vfio_pgsize_bitmap(iommu);
2221 ret = vfio_iommu_iova_build_caps(iommu, &caps);
2226 info.flags |= VFIO_IOMMU_INFO_CAPS;
2228 if (info.argsz < sizeof(info) + caps.size) {
2229 info.argsz = sizeof(info) + caps.size;
2231 vfio_info_cap_shift(&caps, sizeof(info));
2232 if (copy_to_user((void __user *)arg +
2233 sizeof(info), caps.buf,
2238 info.cap_offset = sizeof(info);
2244 return copy_to_user((void __user *)arg, &info, minsz) ?
2247 } else if (cmd == VFIO_IOMMU_MAP_DMA) {
2248 struct vfio_iommu_type1_dma_map map;
2249 uint32_t mask = VFIO_DMA_MAP_FLAG_READ |
2250 VFIO_DMA_MAP_FLAG_WRITE;
2252 minsz = offsetofend(struct vfio_iommu_type1_dma_map, size);
2254 if (copy_from_user(&map, (void __user *)arg, minsz))
2257 if (map.argsz < minsz || map.flags & ~mask)
2260 return vfio_dma_do_map(iommu, &map);
2262 } else if (cmd == VFIO_IOMMU_UNMAP_DMA) {
2263 struct vfio_iommu_type1_dma_unmap unmap;
2266 minsz = offsetofend(struct vfio_iommu_type1_dma_unmap, size);
2268 if (copy_from_user(&unmap, (void __user *)arg, minsz))
2271 if (unmap.argsz < minsz || unmap.flags)
2274 ret = vfio_dma_do_unmap(iommu, &unmap);
2278 return copy_to_user((void __user *)arg, &unmap, minsz) ?
2285 static int vfio_iommu_type1_register_notifier(void *iommu_data,
2286 unsigned long *events,
2287 struct notifier_block *nb)
2289 struct vfio_iommu *iommu = iommu_data;
2291 /* clear known events */
2292 *events &= ~VFIO_IOMMU_NOTIFY_DMA_UNMAP;
2294 /* refuse to register if still events remaining */
2298 return blocking_notifier_chain_register(&iommu->notifier, nb);
2301 static int vfio_iommu_type1_unregister_notifier(void *iommu_data,
2302 struct notifier_block *nb)
2304 struct vfio_iommu *iommu = iommu_data;
2306 return blocking_notifier_chain_unregister(&iommu->notifier, nb);
2309 static int vfio_iommu_type1_dma_rw_chunk(struct vfio_iommu *iommu,
2310 dma_addr_t user_iova, void *data,
2311 size_t count, bool write,
2314 struct mm_struct *mm;
2315 unsigned long vaddr;
2316 struct vfio_dma *dma;
2317 bool kthread = current->mm == NULL;
2322 dma = vfio_find_dma(iommu, user_iova, 1);
2326 if ((write && !(dma->prot & IOMMU_WRITE)) ||
2327 !(dma->prot & IOMMU_READ))
2330 mm = get_task_mm(dma->task);
2337 else if (current->mm != mm)
2340 offset = user_iova - dma->iova;
2342 if (count > dma->size - offset)
2343 count = dma->size - offset;
2345 vaddr = dma->vaddr + offset;
2348 *copied = __copy_to_user((void __user *)vaddr, data,
2351 *copied = __copy_from_user(data, (void __user *)vaddr,
2357 return *copied ? 0 : -EFAULT;
2360 static int vfio_iommu_type1_dma_rw(void *iommu_data, dma_addr_t user_iova,
2361 void *data, size_t count, bool write)
2363 struct vfio_iommu *iommu = iommu_data;
2367 mutex_lock(&iommu->lock);
2369 ret = vfio_iommu_type1_dma_rw_chunk(iommu, user_iova, data,
2370 count, write, &done);
2379 mutex_unlock(&iommu->lock);
2383 static const struct vfio_iommu_driver_ops vfio_iommu_driver_ops_type1 = {
2384 .name = "vfio-iommu-type1",
2385 .owner = THIS_MODULE,
2386 .open = vfio_iommu_type1_open,
2387 .release = vfio_iommu_type1_release,
2388 .ioctl = vfio_iommu_type1_ioctl,
2389 .attach_group = vfio_iommu_type1_attach_group,
2390 .detach_group = vfio_iommu_type1_detach_group,
2391 .pin_pages = vfio_iommu_type1_pin_pages,
2392 .unpin_pages = vfio_iommu_type1_unpin_pages,
2393 .register_notifier = vfio_iommu_type1_register_notifier,
2394 .unregister_notifier = vfio_iommu_type1_unregister_notifier,
2395 .dma_rw = vfio_iommu_type1_dma_rw,
2398 static int __init vfio_iommu_type1_init(void)
2400 return vfio_register_iommu_driver(&vfio_iommu_driver_ops_type1);
2403 static void __exit vfio_iommu_type1_cleanup(void)
2405 vfio_unregister_iommu_driver(&vfio_iommu_driver_ops_type1);
2408 module_init(vfio_iommu_type1_init);
2409 module_exit(vfio_iommu_type1_cleanup);
2411 MODULE_VERSION(DRIVER_VERSION);
2412 MODULE_LICENSE("GPL v2");
2413 MODULE_AUTHOR(DRIVER_AUTHOR);
2414 MODULE_DESCRIPTION(DRIVER_DESC);