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 * userspace pages pinned into memory. We also assume devices and IOMMU
20 * domains are PCI based as the IOMMU API is still centered around a
21 * device/bus interface rather than a group interface.
24 #include <linux/compat.h>
25 #include <linux/device.h>
27 #include <linux/highmem.h>
28 #include <linux/iommu.h>
29 #include <linux/module.h>
31 #include <linux/kthread.h>
32 #include <linux/rbtree.h>
33 #include <linux/sched/signal.h>
34 #include <linux/sched/mm.h>
35 #include <linux/slab.h>
36 #include <linux/uaccess.h>
37 #include <linux/vfio.h>
38 #include <linux/workqueue.h>
39 #include <linux/notifier.h>
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;
67 struct rb_root dma_list;
68 struct list_head device_list;
69 struct mutex device_list_lock;
70 unsigned int dma_avail;
71 unsigned int vaddr_invalid_count;
72 uint64_t pgsize_bitmap;
73 uint64_t num_non_pinned_groups;
76 bool dirty_page_tracking;
77 struct list_head emulated_iommu_groups;
81 struct iommu_domain *domain;
82 struct list_head next;
83 struct list_head group_list;
84 bool fgsp : 1; /* Fine-grained super pages */
85 bool enforce_cache_coherency : 1;
90 dma_addr_t iova; /* Device address */
91 unsigned long vaddr; /* Process virtual addr */
92 size_t size; /* Map size (bytes) */
93 int prot; /* IOMMU_READ/WRITE */
95 bool lock_cap; /* capable(CAP_IPC_LOCK) */
97 struct task_struct *task;
98 struct rb_root pfn_list; /* Ex-user pinned pfn list */
99 unsigned long *bitmap;
100 struct mm_struct *mm;
105 struct page **pages; /* for pin_user_pages_remote */
106 struct page *fallback_page; /* if pages alloc fails */
107 int capacity; /* length of pages array */
108 int size; /* of batch currently */
109 int offset; /* of next entry in pages */
112 struct vfio_iommu_group {
113 struct iommu_group *iommu_group;
114 struct list_head next;
115 bool pinned_page_dirty_scope;
119 struct list_head list;
125 * Guest RAM pinning working set or DMA target
129 dma_addr_t iova; /* Device address */
130 unsigned long pfn; /* Host pfn */
131 unsigned int ref_count;
134 struct vfio_regions {
135 struct list_head list;
141 #define DIRTY_BITMAP_BYTES(n) (ALIGN(n, BITS_PER_TYPE(u64)) / BITS_PER_BYTE)
144 * Input argument of number of bits to bitmap_set() is unsigned integer, which
145 * further casts to signed integer for unaligned multi-bit operation,
147 * Then maximum bitmap size supported is 2^31 bits divided by 2^3 bits/byte,
148 * that is 2^28 (256 MB) which maps to 2^31 * 2^12 = 2^43 (8TB) on 4K page
151 #define DIRTY_BITMAP_PAGES_MAX ((u64)INT_MAX)
152 #define DIRTY_BITMAP_SIZE_MAX DIRTY_BITMAP_BYTES(DIRTY_BITMAP_PAGES_MAX)
154 static int put_pfn(unsigned long pfn, int prot);
156 static struct vfio_iommu_group*
157 vfio_iommu_find_iommu_group(struct vfio_iommu *iommu,
158 struct iommu_group *iommu_group);
161 * This code handles mapping and unmapping of user data buffers
162 * into DMA'ble space using the IOMMU
165 static struct vfio_dma *vfio_find_dma(struct vfio_iommu *iommu,
166 dma_addr_t start, size_t size)
168 struct rb_node *node = iommu->dma_list.rb_node;
171 struct vfio_dma *dma = rb_entry(node, struct vfio_dma, node);
173 if (start + size <= dma->iova)
174 node = node->rb_left;
175 else if (start >= dma->iova + dma->size)
176 node = node->rb_right;
184 static struct rb_node *vfio_find_dma_first_node(struct vfio_iommu *iommu,
185 dma_addr_t start, u64 size)
187 struct rb_node *res = NULL;
188 struct rb_node *node = iommu->dma_list.rb_node;
189 struct vfio_dma *dma_res = NULL;
192 struct vfio_dma *dma = rb_entry(node, struct vfio_dma, node);
194 if (start < dma->iova + dma->size) {
197 if (start >= dma->iova)
199 node = node->rb_left;
201 node = node->rb_right;
204 if (res && size && dma_res->iova >= start + size)
209 static void vfio_link_dma(struct vfio_iommu *iommu, struct vfio_dma *new)
211 struct rb_node **link = &iommu->dma_list.rb_node, *parent = NULL;
212 struct vfio_dma *dma;
216 dma = rb_entry(parent, struct vfio_dma, node);
218 if (new->iova + new->size <= dma->iova)
219 link = &(*link)->rb_left;
221 link = &(*link)->rb_right;
224 rb_link_node(&new->node, parent, link);
225 rb_insert_color(&new->node, &iommu->dma_list);
228 static void vfio_unlink_dma(struct vfio_iommu *iommu, struct vfio_dma *old)
230 rb_erase(&old->node, &iommu->dma_list);
234 static int vfio_dma_bitmap_alloc(struct vfio_dma *dma, size_t pgsize)
236 uint64_t npages = dma->size / pgsize;
238 if (npages > DIRTY_BITMAP_PAGES_MAX)
242 * Allocate extra 64 bits that are used to calculate shift required for
243 * bitmap_shift_left() to manipulate and club unaligned number of pages
244 * in adjacent vfio_dma ranges.
246 dma->bitmap = kvzalloc(DIRTY_BITMAP_BYTES(npages) + sizeof(u64),
254 static void vfio_dma_bitmap_free(struct vfio_dma *dma)
260 static void vfio_dma_populate_bitmap(struct vfio_dma *dma, size_t pgsize)
263 unsigned long pgshift = __ffs(pgsize);
265 for (p = rb_first(&dma->pfn_list); p; p = rb_next(p)) {
266 struct vfio_pfn *vpfn = rb_entry(p, struct vfio_pfn, node);
268 bitmap_set(dma->bitmap, (vpfn->iova - dma->iova) >> pgshift, 1);
272 static void vfio_iommu_populate_bitmap_full(struct vfio_iommu *iommu)
275 unsigned long pgshift = __ffs(iommu->pgsize_bitmap);
277 for (n = rb_first(&iommu->dma_list); n; n = rb_next(n)) {
278 struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
280 bitmap_set(dma->bitmap, 0, dma->size >> pgshift);
284 static int vfio_dma_bitmap_alloc_all(struct vfio_iommu *iommu, size_t pgsize)
288 for (n = rb_first(&iommu->dma_list); n; n = rb_next(n)) {
289 struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
292 ret = vfio_dma_bitmap_alloc(dma, pgsize);
296 for (p = rb_prev(n); p; p = rb_prev(p)) {
297 struct vfio_dma *dma = rb_entry(n,
298 struct vfio_dma, node);
300 vfio_dma_bitmap_free(dma);
304 vfio_dma_populate_bitmap(dma, pgsize);
309 static void vfio_dma_bitmap_free_all(struct vfio_iommu *iommu)
313 for (n = rb_first(&iommu->dma_list); n; n = rb_next(n)) {
314 struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
316 vfio_dma_bitmap_free(dma);
321 * Helper Functions for host iova-pfn list
323 static struct vfio_pfn *vfio_find_vpfn(struct vfio_dma *dma, dma_addr_t iova)
325 struct vfio_pfn *vpfn;
326 struct rb_node *node = dma->pfn_list.rb_node;
329 vpfn = rb_entry(node, struct vfio_pfn, node);
331 if (iova < vpfn->iova)
332 node = node->rb_left;
333 else if (iova > vpfn->iova)
334 node = node->rb_right;
341 static void vfio_link_pfn(struct vfio_dma *dma,
342 struct vfio_pfn *new)
344 struct rb_node **link, *parent = NULL;
345 struct vfio_pfn *vpfn;
347 link = &dma->pfn_list.rb_node;
350 vpfn = rb_entry(parent, struct vfio_pfn, node);
352 if (new->iova < vpfn->iova)
353 link = &(*link)->rb_left;
355 link = &(*link)->rb_right;
358 rb_link_node(&new->node, parent, link);
359 rb_insert_color(&new->node, &dma->pfn_list);
362 static void vfio_unlink_pfn(struct vfio_dma *dma, struct vfio_pfn *old)
364 rb_erase(&old->node, &dma->pfn_list);
367 static int vfio_add_to_pfn_list(struct vfio_dma *dma, dma_addr_t iova,
370 struct vfio_pfn *vpfn;
372 vpfn = kzalloc(sizeof(*vpfn), GFP_KERNEL);
379 vfio_link_pfn(dma, vpfn);
383 static void vfio_remove_from_pfn_list(struct vfio_dma *dma,
384 struct vfio_pfn *vpfn)
386 vfio_unlink_pfn(dma, vpfn);
390 static struct vfio_pfn *vfio_iova_get_vfio_pfn(struct vfio_dma *dma,
393 struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
400 static int vfio_iova_put_vfio_pfn(struct vfio_dma *dma, struct vfio_pfn *vpfn)
405 if (!vpfn->ref_count) {
406 ret = put_pfn(vpfn->pfn, dma->prot);
407 vfio_remove_from_pfn_list(dma, vpfn);
412 static int mm_lock_acct(struct task_struct *task, struct mm_struct *mm,
413 bool lock_cap, long npage)
415 int ret = mmap_write_lock_killable(mm);
420 ret = __account_locked_vm(mm, abs(npage), npage > 0, task, lock_cap);
421 mmap_write_unlock(mm);
425 static int vfio_lock_acct(struct vfio_dma *dma, long npage, bool async)
427 struct mm_struct *mm;
434 if (async && !mmget_not_zero(mm))
435 return -ESRCH; /* process exited */
437 ret = mm_lock_acct(dma->task, mm, dma->lock_cap, npage);
439 dma->locked_vm += npage;
448 * Some mappings aren't backed by a struct page, for example an mmap'd
449 * MMIO range for our own or another device. These use a different
450 * pfn conversion and shouldn't be tracked as locked pages.
451 * For compound pages, any driver that sets the reserved bit in head
452 * page needs to set the reserved bit in all subpages to be safe.
454 static bool is_invalid_reserved_pfn(unsigned long pfn)
457 return PageReserved(pfn_to_page(pfn));
462 static int put_pfn(unsigned long pfn, int prot)
464 if (!is_invalid_reserved_pfn(pfn)) {
465 struct page *page = pfn_to_page(pfn);
467 unpin_user_pages_dirty_lock(&page, 1, prot & IOMMU_WRITE);
473 #define VFIO_BATCH_MAX_CAPACITY (PAGE_SIZE / sizeof(struct page *))
475 static void vfio_batch_init(struct vfio_batch *batch)
480 if (unlikely(disable_hugepages))
483 batch->pages = (struct page **) __get_free_page(GFP_KERNEL);
487 batch->capacity = VFIO_BATCH_MAX_CAPACITY;
491 batch->pages = &batch->fallback_page;
495 static void vfio_batch_unpin(struct vfio_batch *batch, struct vfio_dma *dma)
497 while (batch->size) {
498 unsigned long pfn = page_to_pfn(batch->pages[batch->offset]);
500 put_pfn(pfn, dma->prot);
506 static void vfio_batch_fini(struct vfio_batch *batch)
508 if (batch->capacity == VFIO_BATCH_MAX_CAPACITY)
509 free_page((unsigned long)batch->pages);
512 static int follow_fault_pfn(struct vm_area_struct *vma, struct mm_struct *mm,
513 unsigned long vaddr, unsigned long *pfn,
520 ret = follow_pte(vma->vm_mm, vaddr, &ptep, &ptl);
522 bool unlocked = false;
524 ret = fixup_user_fault(mm, vaddr,
526 (write_fault ? FAULT_FLAG_WRITE : 0),
534 ret = follow_pte(vma->vm_mm, vaddr, &ptep, &ptl);
539 if (write_fault && !pte_write(*ptep))
542 *pfn = pte_pfn(*ptep);
544 pte_unmap_unlock(ptep, ptl);
549 * Returns the positive number of pfns successfully obtained or a negative
552 static int vaddr_get_pfns(struct mm_struct *mm, unsigned long vaddr,
553 long npages, int prot, unsigned long *pfn,
556 struct vm_area_struct *vma;
557 unsigned int flags = 0;
560 if (prot & IOMMU_WRITE)
564 ret = pin_user_pages_remote(mm, vaddr, npages, flags | FOLL_LONGTERM,
570 * The zero page is always resident, we don't need to pin it
571 * and it falls into our invalid/reserved test so we don't
572 * unpin in put_pfn(). Unpin all zero pages in the batch here.
574 for (i = 0 ; i < ret; i++) {
575 if (unlikely(is_zero_pfn(page_to_pfn(pages[i]))))
576 unpin_user_page(pages[i]);
579 *pfn = page_to_pfn(pages[0]);
583 vaddr = untagged_addr_remote(mm, vaddr);
586 vma = vma_lookup(mm, vaddr);
588 if (vma && vma->vm_flags & VM_PFNMAP) {
589 ret = follow_fault_pfn(vma, mm, vaddr, pfn, prot & IOMMU_WRITE);
594 if (is_invalid_reserved_pfn(*pfn))
601 mmap_read_unlock(mm);
606 * Attempt to pin pages. We really don't want to track all the pfns and
607 * the iommu can only map chunks of consecutive pfns anyway, so get the
608 * first page and all consecutive pages with the same locking.
610 static long vfio_pin_pages_remote(struct vfio_dma *dma, unsigned long vaddr,
611 long npage, unsigned long *pfn_base,
612 unsigned long limit, struct vfio_batch *batch)
615 struct mm_struct *mm = current->mm;
616 long ret, pinned = 0, lock_acct = 0;
618 dma_addr_t iova = vaddr - dma->vaddr + dma->iova;
620 /* This code path is only user initiated */
625 /* Leftover pages in batch from an earlier call. */
626 *pfn_base = page_to_pfn(batch->pages[batch->offset]);
628 rsvd = is_invalid_reserved_pfn(*pfn_base);
635 /* Empty batch, so refill it. */
636 long req_pages = min_t(long, npage, batch->capacity);
638 ret = vaddr_get_pfns(mm, vaddr, req_pages, dma->prot,
648 rsvd = is_invalid_reserved_pfn(*pfn_base);
653 * pfn is preset for the first iteration of this inner loop and
654 * updated at the end to handle a VM_PFNMAP pfn. In that case,
655 * batch->pages isn't valid (there's no struct page), so allow
656 * batch->pages to be touched only when there's more than one
657 * pfn to check, which guarantees the pfns are from a
661 if (pfn != *pfn_base + pinned ||
662 rsvd != is_invalid_reserved_pfn(pfn))
666 * Reserved pages aren't counted against the user,
667 * externally pinned pages are already counted against
670 if (!rsvd && !vfio_find_vpfn(dma, iova)) {
671 if (!dma->lock_cap &&
672 mm->locked_vm + lock_acct + 1 > limit) {
673 pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n",
674 __func__, limit << PAGE_SHIFT);
691 pfn = page_to_pfn(batch->pages[batch->offset]);
694 if (unlikely(disable_hugepages))
699 ret = vfio_lock_acct(dma, lock_acct, false);
702 if (batch->size == 1 && !batch->offset) {
703 /* May be a VM_PFNMAP pfn, which the batch can't remember. */
704 put_pfn(pfn, dma->prot);
709 if (pinned && !rsvd) {
710 for (pfn = *pfn_base ; pinned ; pfn++, pinned--)
711 put_pfn(pfn, dma->prot);
713 vfio_batch_unpin(batch, dma);
721 static long vfio_unpin_pages_remote(struct vfio_dma *dma, dma_addr_t iova,
722 unsigned long pfn, long npage,
725 long unlocked = 0, locked = 0;
728 for (i = 0; i < npage; i++, iova += PAGE_SIZE) {
729 if (put_pfn(pfn++, dma->prot)) {
731 if (vfio_find_vpfn(dma, iova))
737 vfio_lock_acct(dma, locked - unlocked, true);
742 static int vfio_pin_page_external(struct vfio_dma *dma, unsigned long vaddr,
743 unsigned long *pfn_base, bool do_accounting)
745 struct page *pages[1];
746 struct mm_struct *mm;
750 if (!mmget_not_zero(mm))
753 ret = vaddr_get_pfns(mm, vaddr, 1, dma->prot, pfn_base, pages);
759 if (do_accounting && !is_invalid_reserved_pfn(*pfn_base)) {
760 ret = vfio_lock_acct(dma, 1, false);
762 put_pfn(*pfn_base, dma->prot);
764 pr_warn("%s: Task %s (%d) RLIMIT_MEMLOCK "
765 "(%ld) exceeded\n", __func__,
766 dma->task->comm, task_pid_nr(dma->task),
767 task_rlimit(dma->task, RLIMIT_MEMLOCK));
776 static int vfio_unpin_page_external(struct vfio_dma *dma, dma_addr_t iova,
780 struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
785 unlocked = vfio_iova_put_vfio_pfn(dma, vpfn);
788 vfio_lock_acct(dma, -unlocked, true);
793 static int vfio_iommu_type1_pin_pages(void *iommu_data,
794 struct iommu_group *iommu_group,
795 dma_addr_t user_iova,
799 struct vfio_iommu *iommu = iommu_data;
800 struct vfio_iommu_group *group;
802 unsigned long remote_vaddr;
803 struct vfio_dma *dma;
806 if (!iommu || !pages)
809 /* Supported for v2 version only */
813 mutex_lock(&iommu->lock);
815 if (WARN_ONCE(iommu->vaddr_invalid_count,
816 "vfio_pin_pages not allowed with VFIO_UPDATE_VADDR\n")) {
821 /* Fail if no dma_umap notifier is registered */
822 if (list_empty(&iommu->device_list)) {
828 * If iommu capable domain exist in the container then all pages are
829 * already pinned and accounted. Accounting should be done if there is no
830 * iommu capable domain in the container.
832 do_accounting = list_empty(&iommu->domain_list);
834 for (i = 0; i < npage; i++) {
835 unsigned long phys_pfn;
837 struct vfio_pfn *vpfn;
839 iova = user_iova + PAGE_SIZE * i;
840 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
846 if ((dma->prot & prot) != prot) {
851 vpfn = vfio_iova_get_vfio_pfn(dma, iova);
853 pages[i] = pfn_to_page(vpfn->pfn);
857 remote_vaddr = dma->vaddr + (iova - dma->iova);
858 ret = vfio_pin_page_external(dma, remote_vaddr, &phys_pfn,
863 if (!pfn_valid(phys_pfn)) {
868 ret = vfio_add_to_pfn_list(dma, iova, phys_pfn);
870 if (put_pfn(phys_pfn, dma->prot) && do_accounting)
871 vfio_lock_acct(dma, -1, true);
875 pages[i] = pfn_to_page(phys_pfn);
877 if (iommu->dirty_page_tracking) {
878 unsigned long pgshift = __ffs(iommu->pgsize_bitmap);
881 * Bitmap populated with the smallest supported page
884 bitmap_set(dma->bitmap,
885 (iova - dma->iova) >> pgshift, 1);
890 group = vfio_iommu_find_iommu_group(iommu, iommu_group);
891 if (!group->pinned_page_dirty_scope) {
892 group->pinned_page_dirty_scope = true;
893 iommu->num_non_pinned_groups--;
900 for (j = 0; j < i; j++) {
903 iova = user_iova + PAGE_SIZE * j;
904 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
905 vfio_unpin_page_external(dma, iova, do_accounting);
909 mutex_unlock(&iommu->lock);
913 static void vfio_iommu_type1_unpin_pages(void *iommu_data,
914 dma_addr_t user_iova, int npage)
916 struct vfio_iommu *iommu = iommu_data;
920 /* Supported for v2 version only */
921 if (WARN_ON(!iommu->v2))
924 mutex_lock(&iommu->lock);
926 do_accounting = list_empty(&iommu->domain_list);
927 for (i = 0; i < npage; i++) {
928 dma_addr_t iova = user_iova + PAGE_SIZE * i;
929 struct vfio_dma *dma;
931 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
935 vfio_unpin_page_external(dma, iova, do_accounting);
938 mutex_unlock(&iommu->lock);
943 static long vfio_sync_unpin(struct vfio_dma *dma, struct vfio_domain *domain,
944 struct list_head *regions,
945 struct iommu_iotlb_gather *iotlb_gather)
948 struct vfio_regions *entry, *next;
950 iommu_iotlb_sync(domain->domain, iotlb_gather);
952 list_for_each_entry_safe(entry, next, regions, list) {
953 unlocked += vfio_unpin_pages_remote(dma,
955 entry->phys >> PAGE_SHIFT,
956 entry->len >> PAGE_SHIFT,
958 list_del(&entry->list);
968 * Generally, VFIO needs to unpin remote pages after each IOTLB flush.
969 * Therefore, when using IOTLB flush sync interface, VFIO need to keep track
970 * of these regions (currently using a list).
972 * This value specifies maximum number of regions for each IOTLB flush sync.
974 #define VFIO_IOMMU_TLB_SYNC_MAX 512
976 static size_t unmap_unpin_fast(struct vfio_domain *domain,
977 struct vfio_dma *dma, dma_addr_t *iova,
978 size_t len, phys_addr_t phys, long *unlocked,
979 struct list_head *unmapped_list,
981 struct iommu_iotlb_gather *iotlb_gather)
984 struct vfio_regions *entry = kzalloc(sizeof(*entry), GFP_KERNEL);
987 unmapped = iommu_unmap_fast(domain->domain, *iova, len,
995 entry->len = unmapped;
996 list_add_tail(&entry->list, unmapped_list);
1004 * Sync if the number of fast-unmap regions hits the limit
1005 * or in case of errors.
1007 if (*unmapped_cnt >= VFIO_IOMMU_TLB_SYNC_MAX || !unmapped) {
1008 *unlocked += vfio_sync_unpin(dma, domain, unmapped_list,
1016 static size_t unmap_unpin_slow(struct vfio_domain *domain,
1017 struct vfio_dma *dma, dma_addr_t *iova,
1018 size_t len, phys_addr_t phys,
1021 size_t unmapped = iommu_unmap(domain->domain, *iova, len);
1024 *unlocked += vfio_unpin_pages_remote(dma, *iova,
1026 unmapped >> PAGE_SHIFT,
1034 static long vfio_unmap_unpin(struct vfio_iommu *iommu, struct vfio_dma *dma,
1037 dma_addr_t iova = dma->iova, end = dma->iova + dma->size;
1038 struct vfio_domain *domain, *d;
1039 LIST_HEAD(unmapped_region_list);
1040 struct iommu_iotlb_gather iotlb_gather;
1041 int unmapped_region_cnt = 0;
1047 if (list_empty(&iommu->domain_list))
1051 * We use the IOMMU to track the physical addresses, otherwise we'd
1052 * need a much more complicated tracking system. Unfortunately that
1053 * means we need to use one of the iommu domains to figure out the
1054 * pfns to unpin. The rest need to be unmapped in advance so we have
1055 * no iommu translations remaining when the pages are unpinned.
1057 domain = d = list_first_entry(&iommu->domain_list,
1058 struct vfio_domain, next);
1060 list_for_each_entry_continue(d, &iommu->domain_list, next) {
1061 iommu_unmap(d->domain, dma->iova, dma->size);
1065 iommu_iotlb_gather_init(&iotlb_gather);
1066 while (iova < end) {
1067 size_t unmapped, len;
1068 phys_addr_t phys, next;
1070 phys = iommu_iova_to_phys(domain->domain, iova);
1071 if (WARN_ON(!phys)) {
1077 * To optimize for fewer iommu_unmap() calls, each of which
1078 * may require hardware cache flushing, try to find the
1079 * largest contiguous physical memory chunk to unmap.
1081 for (len = PAGE_SIZE;
1082 !domain->fgsp && iova + len < end; len += PAGE_SIZE) {
1083 next = iommu_iova_to_phys(domain->domain, iova + len);
1084 if (next != phys + len)
1089 * First, try to use fast unmap/unpin. In case of failure,
1090 * switch to slow unmap/unpin path.
1092 unmapped = unmap_unpin_fast(domain, dma, &iova, len, phys,
1093 &unlocked, &unmapped_region_list,
1094 &unmapped_region_cnt,
1097 unmapped = unmap_unpin_slow(domain, dma, &iova, len,
1099 if (WARN_ON(!unmapped))
1104 dma->iommu_mapped = false;
1106 if (unmapped_region_cnt) {
1107 unlocked += vfio_sync_unpin(dma, domain, &unmapped_region_list,
1111 if (do_accounting) {
1112 vfio_lock_acct(dma, -unlocked, true);
1118 static void vfio_remove_dma(struct vfio_iommu *iommu, struct vfio_dma *dma)
1120 WARN_ON(!RB_EMPTY_ROOT(&dma->pfn_list));
1121 vfio_unmap_unpin(iommu, dma, true);
1122 vfio_unlink_dma(iommu, dma);
1123 put_task_struct(dma->task);
1125 vfio_dma_bitmap_free(dma);
1126 if (dma->vaddr_invalid)
1127 iommu->vaddr_invalid_count--;
1132 static void vfio_update_pgsize_bitmap(struct vfio_iommu *iommu)
1134 struct vfio_domain *domain;
1136 iommu->pgsize_bitmap = ULONG_MAX;
1138 list_for_each_entry(domain, &iommu->domain_list, next)
1139 iommu->pgsize_bitmap &= domain->domain->pgsize_bitmap;
1142 * In case the IOMMU supports page sizes smaller than PAGE_SIZE
1143 * we pretend PAGE_SIZE is supported and hide sub-PAGE_SIZE sizes.
1144 * That way the user will be able to map/unmap buffers whose size/
1145 * start address is aligned with PAGE_SIZE. Pinning code uses that
1146 * granularity while iommu driver can use the sub-PAGE_SIZE size
1147 * to map the buffer.
1149 if (iommu->pgsize_bitmap & ~PAGE_MASK) {
1150 iommu->pgsize_bitmap &= PAGE_MASK;
1151 iommu->pgsize_bitmap |= PAGE_SIZE;
1155 static int update_user_bitmap(u64 __user *bitmap, struct vfio_iommu *iommu,
1156 struct vfio_dma *dma, dma_addr_t base_iova,
1159 unsigned long pgshift = __ffs(pgsize);
1160 unsigned long nbits = dma->size >> pgshift;
1161 unsigned long bit_offset = (dma->iova - base_iova) >> pgshift;
1162 unsigned long copy_offset = bit_offset / BITS_PER_LONG;
1163 unsigned long shift = bit_offset % BITS_PER_LONG;
1164 unsigned long leftover;
1167 * mark all pages dirty if any IOMMU capable device is not able
1168 * to report dirty pages and all pages are pinned and mapped.
1170 if (iommu->num_non_pinned_groups && dma->iommu_mapped)
1171 bitmap_set(dma->bitmap, 0, nbits);
1174 bitmap_shift_left(dma->bitmap, dma->bitmap, shift,
1177 if (copy_from_user(&leftover,
1178 (void __user *)(bitmap + copy_offset),
1182 bitmap_or(dma->bitmap, dma->bitmap, &leftover, shift);
1185 if (copy_to_user((void __user *)(bitmap + copy_offset), dma->bitmap,
1186 DIRTY_BITMAP_BYTES(nbits + shift)))
1192 static int vfio_iova_dirty_bitmap(u64 __user *bitmap, struct vfio_iommu *iommu,
1193 dma_addr_t iova, size_t size, size_t pgsize)
1195 struct vfio_dma *dma;
1197 unsigned long pgshift = __ffs(pgsize);
1201 * GET_BITMAP request must fully cover vfio_dma mappings. Multiple
1202 * vfio_dma mappings may be clubbed by specifying large ranges, but
1203 * there must not be any previous mappings bisected by the range.
1204 * An error will be returned if these conditions are not met.
1206 dma = vfio_find_dma(iommu, iova, 1);
1207 if (dma && dma->iova != iova)
1210 dma = vfio_find_dma(iommu, iova + size - 1, 0);
1211 if (dma && dma->iova + dma->size != iova + size)
1214 for (n = rb_first(&iommu->dma_list); n; n = rb_next(n)) {
1215 struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
1217 if (dma->iova < iova)
1220 if (dma->iova > iova + size - 1)
1223 ret = update_user_bitmap(bitmap, iommu, dma, iova, pgsize);
1228 * Re-populate bitmap to include all pinned pages which are
1229 * considered as dirty but exclude pages which are unpinned and
1230 * pages which are marked dirty by vfio_dma_rw()
1232 bitmap_clear(dma->bitmap, 0, dma->size >> pgshift);
1233 vfio_dma_populate_bitmap(dma, pgsize);
1238 static int verify_bitmap_size(uint64_t npages, uint64_t bitmap_size)
1240 if (!npages || !bitmap_size || (bitmap_size > DIRTY_BITMAP_SIZE_MAX) ||
1241 (bitmap_size < DIRTY_BITMAP_BYTES(npages)))
1248 * Notify VFIO drivers using vfio_register_emulated_iommu_dev() to invalidate
1249 * and unmap iovas within the range we're about to unmap. Drivers MUST unpin
1250 * pages in response to an invalidation.
1252 static void vfio_notify_dma_unmap(struct vfio_iommu *iommu,
1253 struct vfio_dma *dma)
1255 struct vfio_device *device;
1257 if (list_empty(&iommu->device_list))
1261 * The device is expected to call vfio_unpin_pages() for any IOVA it has
1262 * pinned within the range. Since vfio_unpin_pages() will eventually
1263 * call back down to this code and try to obtain the iommu->lock we must
1266 mutex_lock(&iommu->device_list_lock);
1267 mutex_unlock(&iommu->lock);
1269 list_for_each_entry(device, &iommu->device_list, iommu_entry)
1270 device->ops->dma_unmap(device, dma->iova, dma->size);
1272 mutex_unlock(&iommu->device_list_lock);
1273 mutex_lock(&iommu->lock);
1276 static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
1277 struct vfio_iommu_type1_dma_unmap *unmap,
1278 struct vfio_bitmap *bitmap)
1280 struct vfio_dma *dma, *dma_last = NULL;
1281 size_t unmapped = 0, pgsize;
1282 int ret = -EINVAL, retries = 0;
1283 unsigned long pgshift;
1284 dma_addr_t iova = unmap->iova;
1285 u64 size = unmap->size;
1286 bool unmap_all = unmap->flags & VFIO_DMA_UNMAP_FLAG_ALL;
1287 bool invalidate_vaddr = unmap->flags & VFIO_DMA_UNMAP_FLAG_VADDR;
1288 struct rb_node *n, *first_n;
1290 mutex_lock(&iommu->lock);
1292 /* Cannot update vaddr if mdev is present. */
1293 if (invalidate_vaddr && !list_empty(&iommu->emulated_iommu_groups)) {
1298 pgshift = __ffs(iommu->pgsize_bitmap);
1299 pgsize = (size_t)1 << pgshift;
1301 if (iova & (pgsize - 1))
1308 } else if (!size || size & (pgsize - 1) ||
1309 iova + size - 1 < iova || size > SIZE_MAX) {
1313 /* When dirty tracking is enabled, allow only min supported pgsize */
1314 if ((unmap->flags & VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP) &&
1315 (!iommu->dirty_page_tracking || (bitmap->pgsize != pgsize))) {
1319 WARN_ON((pgsize - 1) & PAGE_MASK);
1322 * vfio-iommu-type1 (v1) - User mappings were coalesced together to
1323 * avoid tracking individual mappings. This means that the granularity
1324 * of the original mapping was lost and the user was allowed to attempt
1325 * to unmap any range. Depending on the contiguousness of physical
1326 * memory and page sizes supported by the IOMMU, arbitrary unmaps may
1327 * or may not have worked. We only guaranteed unmap granularity
1328 * matching the original mapping; even though it was untracked here,
1329 * the original mappings are reflected in IOMMU mappings. This
1330 * resulted in a couple unusual behaviors. First, if a range is not
1331 * able to be unmapped, ex. a set of 4k pages that was mapped as a
1332 * 2M hugepage into the IOMMU, the unmap ioctl returns success but with
1333 * a zero sized unmap. Also, if an unmap request overlaps the first
1334 * address of a hugepage, the IOMMU will unmap the entire hugepage.
1335 * This also returns success and the returned unmap size reflects the
1336 * actual size unmapped.
1338 * We attempt to maintain compatibility with this "v1" interface, but
1339 * we take control out of the hands of the IOMMU. Therefore, an unmap
1340 * request offset from the beginning of the original mapping will
1341 * return success with zero sized unmap. And an unmap request covering
1342 * the first iova of mapping will unmap the entire range.
1344 * The v2 version of this interface intends to be more deterministic.
1345 * Unmap requests must fully cover previous mappings. Multiple
1346 * mappings may still be unmaped by specifying large ranges, but there
1347 * must not be any previous mappings bisected by the range. An error
1348 * will be returned if these conditions are not met. The v2 interface
1349 * will only return success and a size of zero if there were no
1350 * mappings within the range.
1352 if (iommu->v2 && !unmap_all) {
1353 dma = vfio_find_dma(iommu, iova, 1);
1354 if (dma && dma->iova != iova)
1357 dma = vfio_find_dma(iommu, iova + size - 1, 0);
1358 if (dma && dma->iova + dma->size != iova + size)
1363 n = first_n = vfio_find_dma_first_node(iommu, iova, size);
1366 dma = rb_entry(n, struct vfio_dma, node);
1367 if (dma->iova >= iova + size)
1370 if (!iommu->v2 && iova > dma->iova)
1373 if (invalidate_vaddr) {
1374 if (dma->vaddr_invalid) {
1375 struct rb_node *last_n = n;
1377 for (n = first_n; n != last_n; n = rb_next(n)) {
1379 struct vfio_dma, node);
1380 dma->vaddr_invalid = false;
1381 iommu->vaddr_invalid_count--;
1387 dma->vaddr_invalid = true;
1388 iommu->vaddr_invalid_count++;
1389 unmapped += dma->size;
1394 if (!RB_EMPTY_ROOT(&dma->pfn_list)) {
1395 if (dma_last == dma) {
1396 BUG_ON(++retries > 10);
1402 vfio_notify_dma_unmap(iommu, dma);
1406 if (unmap->flags & VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP) {
1407 ret = update_user_bitmap(bitmap->data, iommu, dma,
1413 unmapped += dma->size;
1415 vfio_remove_dma(iommu, dma);
1419 mutex_unlock(&iommu->lock);
1421 /* Report how much was unmapped */
1422 unmap->size = unmapped;
1427 static int vfio_iommu_map(struct vfio_iommu *iommu, dma_addr_t iova,
1428 unsigned long pfn, long npage, int prot)
1430 struct vfio_domain *d;
1433 list_for_each_entry(d, &iommu->domain_list, next) {
1434 ret = iommu_map(d->domain, iova, (phys_addr_t)pfn << PAGE_SHIFT,
1435 npage << PAGE_SHIFT, prot | IOMMU_CACHE,
1446 list_for_each_entry_continue_reverse(d, &iommu->domain_list, next) {
1447 iommu_unmap(d->domain, iova, npage << PAGE_SHIFT);
1454 static int vfio_pin_map_dma(struct vfio_iommu *iommu, struct vfio_dma *dma,
1457 dma_addr_t iova = dma->iova;
1458 unsigned long vaddr = dma->vaddr;
1459 struct vfio_batch batch;
1460 size_t size = map_size;
1462 unsigned long pfn, limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1465 vfio_batch_init(&batch);
1468 /* Pin a contiguous chunk of memory */
1469 npage = vfio_pin_pages_remote(dma, vaddr + dma->size,
1470 size >> PAGE_SHIFT, &pfn, limit,
1479 ret = vfio_iommu_map(iommu, iova + dma->size, pfn, npage,
1482 vfio_unpin_pages_remote(dma, iova + dma->size, pfn,
1484 vfio_batch_unpin(&batch, dma);
1488 size -= npage << PAGE_SHIFT;
1489 dma->size += npage << PAGE_SHIFT;
1492 vfio_batch_fini(&batch);
1493 dma->iommu_mapped = true;
1496 vfio_remove_dma(iommu, dma);
1502 * Check dma map request is within a valid iova range
1504 static bool vfio_iommu_iova_dma_valid(struct vfio_iommu *iommu,
1505 dma_addr_t start, dma_addr_t end)
1507 struct list_head *iova = &iommu->iova_list;
1508 struct vfio_iova *node;
1510 list_for_each_entry(node, iova, list) {
1511 if (start >= node->start && end <= node->end)
1516 * Check for list_empty() as well since a container with
1517 * a single mdev device will have an empty list.
1519 return list_empty(iova);
1522 static int vfio_change_dma_owner(struct vfio_dma *dma)
1524 struct task_struct *task = current->group_leader;
1525 struct mm_struct *mm = current->mm;
1526 long npage = dma->locked_vm;
1533 lock_cap = capable(CAP_IPC_LOCK);
1534 ret = mm_lock_acct(task, mm, lock_cap, npage);
1538 if (mmget_not_zero(dma->mm)) {
1539 mm_lock_acct(dma->task, dma->mm, dma->lock_cap, -npage);
1543 if (dma->task != task) {
1544 put_task_struct(dma->task);
1545 dma->task = get_task_struct(task);
1550 dma->lock_cap = lock_cap;
1554 static int vfio_dma_do_map(struct vfio_iommu *iommu,
1555 struct vfio_iommu_type1_dma_map *map)
1557 bool set_vaddr = map->flags & VFIO_DMA_MAP_FLAG_VADDR;
1558 dma_addr_t iova = map->iova;
1559 unsigned long vaddr = map->vaddr;
1560 size_t size = map->size;
1561 int ret = 0, prot = 0;
1563 struct vfio_dma *dma;
1565 /* Verify that none of our __u64 fields overflow */
1566 if (map->size != size || map->vaddr != vaddr || map->iova != iova)
1569 /* READ/WRITE from device perspective */
1570 if (map->flags & VFIO_DMA_MAP_FLAG_WRITE)
1571 prot |= IOMMU_WRITE;
1572 if (map->flags & VFIO_DMA_MAP_FLAG_READ)
1575 if ((prot && set_vaddr) || (!prot && !set_vaddr))
1578 mutex_lock(&iommu->lock);
1580 pgsize = (size_t)1 << __ffs(iommu->pgsize_bitmap);
1582 WARN_ON((pgsize - 1) & PAGE_MASK);
1584 if (!size || (size | iova | vaddr) & (pgsize - 1)) {
1589 /* Don't allow IOVA or virtual address wrap */
1590 if (iova + size - 1 < iova || vaddr + size - 1 < vaddr) {
1595 dma = vfio_find_dma(iommu, iova, size);
1599 } else if (!dma->vaddr_invalid || dma->iova != iova ||
1600 dma->size != size) {
1603 ret = vfio_change_dma_owner(dma);
1607 dma->vaddr_invalid = false;
1608 iommu->vaddr_invalid_count--;
1616 if (!iommu->dma_avail) {
1621 if (!vfio_iommu_iova_dma_valid(iommu, iova, iova + size - 1)) {
1626 dma = kzalloc(sizeof(*dma), GFP_KERNEL);
1638 * We need to be able to both add to a task's locked memory and test
1639 * against the locked memory limit and we need to be able to do both
1640 * outside of this call path as pinning can be asynchronous via the
1641 * external interfaces for mdev devices. RLIMIT_MEMLOCK requires a
1642 * task_struct. Save the group_leader so that all DMA tracking uses
1643 * the same task, to make debugging easier. VM locked pages requires
1644 * an mm_struct, so grab the mm in case the task dies.
1646 get_task_struct(current->group_leader);
1647 dma->task = current->group_leader;
1648 dma->lock_cap = capable(CAP_IPC_LOCK);
1649 dma->mm = current->mm;
1652 dma->pfn_list = RB_ROOT;
1654 /* Insert zero-sized and grow as we map chunks of it */
1655 vfio_link_dma(iommu, dma);
1657 /* Don't pin and map if container doesn't contain IOMMU capable domain*/
1658 if (list_empty(&iommu->domain_list))
1661 ret = vfio_pin_map_dma(iommu, dma, size);
1663 if (!ret && iommu->dirty_page_tracking) {
1664 ret = vfio_dma_bitmap_alloc(dma, pgsize);
1666 vfio_remove_dma(iommu, dma);
1670 mutex_unlock(&iommu->lock);
1674 static int vfio_iommu_replay(struct vfio_iommu *iommu,
1675 struct vfio_domain *domain)
1677 struct vfio_batch batch;
1678 struct vfio_domain *d = NULL;
1680 unsigned long limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1683 /* Arbitrarily pick the first domain in the list for lookups */
1684 if (!list_empty(&iommu->domain_list))
1685 d = list_first_entry(&iommu->domain_list,
1686 struct vfio_domain, next);
1688 vfio_batch_init(&batch);
1690 n = rb_first(&iommu->dma_list);
1692 for (; n; n = rb_next(n)) {
1693 struct vfio_dma *dma;
1696 dma = rb_entry(n, struct vfio_dma, node);
1699 while (iova < dma->iova + dma->size) {
1703 if (dma->iommu_mapped) {
1707 if (WARN_ON(!d)) { /* mapped w/o a domain?! */
1712 phys = iommu_iova_to_phys(d->domain, iova);
1714 if (WARN_ON(!phys)) {
1722 while (i < dma->iova + dma->size &&
1723 p == iommu_iova_to_phys(d->domain, i)) {
1730 unsigned long vaddr = dma->vaddr +
1732 size_t n = dma->iova + dma->size - iova;
1735 npage = vfio_pin_pages_remote(dma, vaddr,
1745 phys = pfn << PAGE_SHIFT;
1746 size = npage << PAGE_SHIFT;
1749 ret = iommu_map(domain->domain, iova, phys, size,
1750 dma->prot | IOMMU_CACHE, GFP_KERNEL);
1752 if (!dma->iommu_mapped) {
1753 vfio_unpin_pages_remote(dma, iova,
1757 vfio_batch_unpin(&batch, dma);
1766 /* All dmas are now mapped, defer to second tree walk for unwind */
1767 for (n = rb_first(&iommu->dma_list); n; n = rb_next(n)) {
1768 struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
1770 dma->iommu_mapped = true;
1773 vfio_batch_fini(&batch);
1777 for (; n; n = rb_prev(n)) {
1778 struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
1781 if (dma->iommu_mapped) {
1782 iommu_unmap(domain->domain, dma->iova, dma->size);
1787 while (iova < dma->iova + dma->size) {
1788 phys_addr_t phys, p;
1792 phys = iommu_iova_to_phys(domain->domain, iova);
1801 while (i < dma->iova + dma->size &&
1802 p == iommu_iova_to_phys(domain->domain, i)) {
1808 iommu_unmap(domain->domain, iova, size);
1809 vfio_unpin_pages_remote(dma, iova, phys >> PAGE_SHIFT,
1810 size >> PAGE_SHIFT, true);
1814 vfio_batch_fini(&batch);
1819 * We change our unmap behavior slightly depending on whether the IOMMU
1820 * supports fine-grained superpages. IOMMUs like AMD-Vi will use a superpage
1821 * for practically any contiguous power-of-two mapping we give it. This means
1822 * we don't need to look for contiguous chunks ourselves to make unmapping
1823 * more efficient. On IOMMUs with coarse-grained super pages, like Intel VT-d
1824 * with discrete 2M/1G/512G/1T superpages, identifying contiguous chunks
1825 * significantly boosts non-hugetlbfs mappings and doesn't seem to hurt when
1826 * hugetlbfs is in use.
1828 static void vfio_test_domain_fgsp(struct vfio_domain *domain, struct list_head *regions)
1830 int ret, order = get_order(PAGE_SIZE * 2);
1831 struct vfio_iova *region;
1835 pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, order);
1839 list_for_each_entry(region, regions, list) {
1840 start = ALIGN(region->start, PAGE_SIZE * 2);
1841 if (start >= region->end || (region->end - start < PAGE_SIZE * 2))
1844 ret = iommu_map(domain->domain, start, page_to_phys(pages), PAGE_SIZE * 2,
1845 IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE, GFP_KERNEL);
1847 size_t unmapped = iommu_unmap(domain->domain, start, PAGE_SIZE);
1849 if (unmapped == PAGE_SIZE)
1850 iommu_unmap(domain->domain, start + PAGE_SIZE, PAGE_SIZE);
1852 domain->fgsp = true;
1857 __free_pages(pages, order);
1860 static struct vfio_iommu_group *find_iommu_group(struct vfio_domain *domain,
1861 struct iommu_group *iommu_group)
1863 struct vfio_iommu_group *g;
1865 list_for_each_entry(g, &domain->group_list, next) {
1866 if (g->iommu_group == iommu_group)
1873 static struct vfio_iommu_group*
1874 vfio_iommu_find_iommu_group(struct vfio_iommu *iommu,
1875 struct iommu_group *iommu_group)
1877 struct vfio_iommu_group *group;
1878 struct vfio_domain *domain;
1880 list_for_each_entry(domain, &iommu->domain_list, next) {
1881 group = find_iommu_group(domain, iommu_group);
1886 list_for_each_entry(group, &iommu->emulated_iommu_groups, next)
1887 if (group->iommu_group == iommu_group)
1892 static bool vfio_iommu_has_sw_msi(struct list_head *group_resv_regions,
1895 struct iommu_resv_region *region;
1898 list_for_each_entry(region, group_resv_regions, list) {
1900 * The presence of any 'real' MSI regions should take
1901 * precedence over the software-managed one if the
1902 * IOMMU driver happens to advertise both types.
1904 if (region->type == IOMMU_RESV_MSI) {
1909 if (region->type == IOMMU_RESV_SW_MSI) {
1910 *base = region->start;
1919 * This is a helper function to insert an address range to iova list.
1920 * The list is initially created with a single entry corresponding to
1921 * the IOMMU domain geometry to which the device group is attached.
1922 * The list aperture gets modified when a new domain is added to the
1923 * container if the new aperture doesn't conflict with the current one
1924 * or with any existing dma mappings. The list is also modified to
1925 * exclude any reserved regions associated with the device group.
1927 static int vfio_iommu_iova_insert(struct list_head *head,
1928 dma_addr_t start, dma_addr_t end)
1930 struct vfio_iova *region;
1932 region = kmalloc(sizeof(*region), GFP_KERNEL);
1936 INIT_LIST_HEAD(®ion->list);
1937 region->start = start;
1940 list_add_tail(®ion->list, head);
1945 * Check the new iommu aperture conflicts with existing aper or with any
1946 * existing dma mappings.
1948 static bool vfio_iommu_aper_conflict(struct vfio_iommu *iommu,
1949 dma_addr_t start, dma_addr_t end)
1951 struct vfio_iova *first, *last;
1952 struct list_head *iova = &iommu->iova_list;
1954 if (list_empty(iova))
1957 /* Disjoint sets, return conflict */
1958 first = list_first_entry(iova, struct vfio_iova, list);
1959 last = list_last_entry(iova, struct vfio_iova, list);
1960 if (start > last->end || end < first->start)
1963 /* Check for any existing dma mappings below the new start */
1964 if (start > first->start) {
1965 if (vfio_find_dma(iommu, first->start, start - first->start))
1969 /* Check for any existing dma mappings beyond the new end */
1970 if (end < last->end) {
1971 if (vfio_find_dma(iommu, end + 1, last->end - end))
1979 * Resize iommu iova aperture window. This is called only if the new
1980 * aperture has no conflict with existing aperture and dma mappings.
1982 static int vfio_iommu_aper_resize(struct list_head *iova,
1983 dma_addr_t start, dma_addr_t end)
1985 struct vfio_iova *node, *next;
1987 if (list_empty(iova))
1988 return vfio_iommu_iova_insert(iova, start, end);
1990 /* Adjust iova list start */
1991 list_for_each_entry_safe(node, next, iova, list) {
1992 if (start < node->start)
1994 if (start >= node->start && start < node->end) {
1995 node->start = start;
1998 /* Delete nodes before new start */
1999 list_del(&node->list);
2003 /* Adjust iova list end */
2004 list_for_each_entry_safe(node, next, iova, list) {
2005 if (end > node->end)
2007 if (end > node->start && end <= node->end) {
2011 /* Delete nodes after new end */
2012 list_del(&node->list);
2020 * Check reserved region conflicts with existing dma mappings
2022 static bool vfio_iommu_resv_conflict(struct vfio_iommu *iommu,
2023 struct list_head *resv_regions)
2025 struct iommu_resv_region *region;
2027 /* Check for conflict with existing dma mappings */
2028 list_for_each_entry(region, resv_regions, list) {
2029 if (region->type == IOMMU_RESV_DIRECT_RELAXABLE)
2032 if (vfio_find_dma(iommu, region->start, region->length))
2040 * Check iova region overlap with reserved regions and
2041 * exclude them from the iommu iova range
2043 static int vfio_iommu_resv_exclude(struct list_head *iova,
2044 struct list_head *resv_regions)
2046 struct iommu_resv_region *resv;
2047 struct vfio_iova *n, *next;
2049 list_for_each_entry(resv, resv_regions, list) {
2050 phys_addr_t start, end;
2052 if (resv->type == IOMMU_RESV_DIRECT_RELAXABLE)
2055 start = resv->start;
2056 end = resv->start + resv->length - 1;
2058 list_for_each_entry_safe(n, next, iova, list) {
2062 if (start > n->end || end < n->start)
2065 * Insert a new node if current node overlaps with the
2066 * reserve region to exclude that from valid iova range.
2067 * Note that, new node is inserted before the current
2068 * node and finally the current node is deleted keeping
2069 * the list updated and sorted.
2071 if (start > n->start)
2072 ret = vfio_iommu_iova_insert(&n->list, n->start,
2074 if (!ret && end < n->end)
2075 ret = vfio_iommu_iova_insert(&n->list, end + 1,
2085 if (list_empty(iova))
2091 static void vfio_iommu_resv_free(struct list_head *resv_regions)
2093 struct iommu_resv_region *n, *next;
2095 list_for_each_entry_safe(n, next, resv_regions, list) {
2101 static void vfio_iommu_iova_free(struct list_head *iova)
2103 struct vfio_iova *n, *next;
2105 list_for_each_entry_safe(n, next, iova, list) {
2111 static int vfio_iommu_iova_get_copy(struct vfio_iommu *iommu,
2112 struct list_head *iova_copy)
2114 struct list_head *iova = &iommu->iova_list;
2115 struct vfio_iova *n;
2118 list_for_each_entry(n, iova, list) {
2119 ret = vfio_iommu_iova_insert(iova_copy, n->start, n->end);
2127 vfio_iommu_iova_free(iova_copy);
2131 static void vfio_iommu_iova_insert_copy(struct vfio_iommu *iommu,
2132 struct list_head *iova_copy)
2134 struct list_head *iova = &iommu->iova_list;
2136 vfio_iommu_iova_free(iova);
2138 list_splice_tail(iova_copy, iova);
2141 static int vfio_iommu_domain_alloc(struct device *dev, void *data)
2143 struct iommu_domain **domain = data;
2145 *domain = iommu_domain_alloc(dev->bus);
2146 return 1; /* Don't iterate */
2149 static int vfio_iommu_type1_attach_group(void *iommu_data,
2150 struct iommu_group *iommu_group, enum vfio_group_type type)
2152 struct vfio_iommu *iommu = iommu_data;
2153 struct vfio_iommu_group *group;
2154 struct vfio_domain *domain, *d;
2156 phys_addr_t resv_msi_base = 0;
2157 struct iommu_domain_geometry *geo;
2158 LIST_HEAD(iova_copy);
2159 LIST_HEAD(group_resv_regions);
2162 mutex_lock(&iommu->lock);
2164 /* Attach could require pinning, so disallow while vaddr is invalid. */
2165 if (iommu->vaddr_invalid_count)
2168 /* Check for duplicates */
2170 if (vfio_iommu_find_iommu_group(iommu, iommu_group))
2174 group = kzalloc(sizeof(*group), GFP_KERNEL);
2177 group->iommu_group = iommu_group;
2179 if (type == VFIO_EMULATED_IOMMU) {
2180 list_add(&group->next, &iommu->emulated_iommu_groups);
2182 * An emulated IOMMU group cannot dirty memory directly, it can
2183 * only use interfaces that provide dirty tracking.
2184 * The iommu scope can only be promoted with the addition of a
2185 * dirty tracking group.
2187 group->pinned_page_dirty_scope = true;
2193 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2195 goto out_free_group;
2198 * Going via the iommu_group iterator avoids races, and trivially gives
2199 * us a representative device for the IOMMU API call. We don't actually
2200 * want to iterate beyond the first device (if any).
2203 iommu_group_for_each_dev(iommu_group, &domain->domain,
2204 vfio_iommu_domain_alloc);
2205 if (!domain->domain)
2206 goto out_free_domain;
2208 if (iommu->nesting) {
2209 ret = iommu_enable_nesting(domain->domain);
2214 ret = iommu_attach_group(domain->domain, group->iommu_group);
2218 /* Get aperture info */
2219 geo = &domain->domain->geometry;
2220 if (vfio_iommu_aper_conflict(iommu, geo->aperture_start,
2221 geo->aperture_end)) {
2226 ret = iommu_get_group_resv_regions(iommu_group, &group_resv_regions);
2230 if (vfio_iommu_resv_conflict(iommu, &group_resv_regions)) {
2236 * We don't want to work on the original iova list as the list
2237 * gets modified and in case of failure we have to retain the
2238 * original list. Get a copy here.
2240 ret = vfio_iommu_iova_get_copy(iommu, &iova_copy);
2244 ret = vfio_iommu_aper_resize(&iova_copy, geo->aperture_start,
2249 ret = vfio_iommu_resv_exclude(&iova_copy, &group_resv_regions);
2253 resv_msi = vfio_iommu_has_sw_msi(&group_resv_regions, &resv_msi_base);
2255 INIT_LIST_HEAD(&domain->group_list);
2256 list_add(&group->next, &domain->group_list);
2258 if (!allow_unsafe_interrupts &&
2259 !iommu_group_has_isolated_msi(iommu_group)) {
2260 pr_warn("%s: No interrupt remapping support. Use the module param \"allow_unsafe_interrupts\" to enable VFIO IOMMU support on this platform\n",
2267 * If the IOMMU can block non-coherent operations (ie PCIe TLPs with
2268 * no-snoop set) then VFIO always turns this feature on because on Intel
2269 * platforms it optimizes KVM to disable wbinvd emulation.
2271 if (domain->domain->ops->enforce_cache_coherency)
2272 domain->enforce_cache_coherency =
2273 domain->domain->ops->enforce_cache_coherency(
2277 * Try to match an existing compatible domain. We don't want to
2278 * preclude an IOMMU driver supporting multiple bus_types and being
2279 * able to include different bus_types in the same IOMMU domain, so
2280 * we test whether the domains use the same iommu_ops rather than
2281 * testing if they're on the same bus_type.
2283 list_for_each_entry(d, &iommu->domain_list, next) {
2284 if (d->domain->ops == domain->domain->ops &&
2285 d->enforce_cache_coherency ==
2286 domain->enforce_cache_coherency) {
2287 iommu_detach_group(domain->domain, group->iommu_group);
2288 if (!iommu_attach_group(d->domain,
2289 group->iommu_group)) {
2290 list_add(&group->next, &d->group_list);
2291 iommu_domain_free(domain->domain);
2296 ret = iommu_attach_group(domain->domain,
2297 group->iommu_group);
2303 vfio_test_domain_fgsp(domain, &iova_copy);
2305 /* replay mappings on new domains */
2306 ret = vfio_iommu_replay(iommu, domain);
2311 ret = iommu_get_msi_cookie(domain->domain, resv_msi_base);
2312 if (ret && ret != -ENODEV)
2316 list_add(&domain->next, &iommu->domain_list);
2317 vfio_update_pgsize_bitmap(iommu);
2319 /* Delete the old one and insert new iova list */
2320 vfio_iommu_iova_insert_copy(iommu, &iova_copy);
2323 * An iommu backed group can dirty memory directly and therefore
2324 * demotes the iommu scope until it declares itself dirty tracking
2325 * capable via the page pinning interface.
2327 iommu->num_non_pinned_groups++;
2328 mutex_unlock(&iommu->lock);
2329 vfio_iommu_resv_free(&group_resv_regions);
2334 iommu_detach_group(domain->domain, group->iommu_group);
2336 iommu_domain_free(domain->domain);
2337 vfio_iommu_iova_free(&iova_copy);
2338 vfio_iommu_resv_free(&group_resv_regions);
2344 mutex_unlock(&iommu->lock);
2348 static void vfio_iommu_unmap_unpin_all(struct vfio_iommu *iommu)
2350 struct rb_node *node;
2352 while ((node = rb_first(&iommu->dma_list)))
2353 vfio_remove_dma(iommu, rb_entry(node, struct vfio_dma, node));
2356 static void vfio_iommu_unmap_unpin_reaccount(struct vfio_iommu *iommu)
2358 struct rb_node *n, *p;
2360 n = rb_first(&iommu->dma_list);
2361 for (; n; n = rb_next(n)) {
2362 struct vfio_dma *dma;
2363 long locked = 0, unlocked = 0;
2365 dma = rb_entry(n, struct vfio_dma, node);
2366 unlocked += vfio_unmap_unpin(iommu, dma, false);
2367 p = rb_first(&dma->pfn_list);
2368 for (; p; p = rb_next(p)) {
2369 struct vfio_pfn *vpfn = rb_entry(p, struct vfio_pfn,
2372 if (!is_invalid_reserved_pfn(vpfn->pfn))
2375 vfio_lock_acct(dma, locked - unlocked, true);
2380 * Called when a domain is removed in detach. It is possible that
2381 * the removed domain decided the iova aperture window. Modify the
2382 * iova aperture with the smallest window among existing domains.
2384 static void vfio_iommu_aper_expand(struct vfio_iommu *iommu,
2385 struct list_head *iova_copy)
2387 struct vfio_domain *domain;
2388 struct vfio_iova *node;
2389 dma_addr_t start = 0;
2390 dma_addr_t end = (dma_addr_t)~0;
2392 if (list_empty(iova_copy))
2395 list_for_each_entry(domain, &iommu->domain_list, next) {
2396 struct iommu_domain_geometry *geo = &domain->domain->geometry;
2398 if (geo->aperture_start > start)
2399 start = geo->aperture_start;
2400 if (geo->aperture_end < end)
2401 end = geo->aperture_end;
2404 /* Modify aperture limits. The new aper is either same or bigger */
2405 node = list_first_entry(iova_copy, struct vfio_iova, list);
2406 node->start = start;
2407 node = list_last_entry(iova_copy, struct vfio_iova, list);
2412 * Called when a group is detached. The reserved regions for that
2413 * group can be part of valid iova now. But since reserved regions
2414 * may be duplicated among groups, populate the iova valid regions
2417 static int vfio_iommu_resv_refresh(struct vfio_iommu *iommu,
2418 struct list_head *iova_copy)
2420 struct vfio_domain *d;
2421 struct vfio_iommu_group *g;
2422 struct vfio_iova *node;
2423 dma_addr_t start, end;
2424 LIST_HEAD(resv_regions);
2427 if (list_empty(iova_copy))
2430 list_for_each_entry(d, &iommu->domain_list, next) {
2431 list_for_each_entry(g, &d->group_list, next) {
2432 ret = iommu_get_group_resv_regions(g->iommu_group,
2439 node = list_first_entry(iova_copy, struct vfio_iova, list);
2440 start = node->start;
2441 node = list_last_entry(iova_copy, struct vfio_iova, list);
2444 /* purge the iova list and create new one */
2445 vfio_iommu_iova_free(iova_copy);
2447 ret = vfio_iommu_aper_resize(iova_copy, start, end);
2451 /* Exclude current reserved regions from iova ranges */
2452 ret = vfio_iommu_resv_exclude(iova_copy, &resv_regions);
2454 vfio_iommu_resv_free(&resv_regions);
2458 static void vfio_iommu_type1_detach_group(void *iommu_data,
2459 struct iommu_group *iommu_group)
2461 struct vfio_iommu *iommu = iommu_data;
2462 struct vfio_domain *domain;
2463 struct vfio_iommu_group *group;
2464 bool update_dirty_scope = false;
2465 LIST_HEAD(iova_copy);
2467 mutex_lock(&iommu->lock);
2468 list_for_each_entry(group, &iommu->emulated_iommu_groups, next) {
2469 if (group->iommu_group != iommu_group)
2471 update_dirty_scope = !group->pinned_page_dirty_scope;
2472 list_del(&group->next);
2475 if (list_empty(&iommu->emulated_iommu_groups) &&
2476 list_empty(&iommu->domain_list)) {
2477 WARN_ON(!list_empty(&iommu->device_list));
2478 vfio_iommu_unmap_unpin_all(iommu);
2480 goto detach_group_done;
2484 * Get a copy of iova list. This will be used to update
2485 * and to replace the current one later. Please note that
2486 * we will leave the original list as it is if update fails.
2488 vfio_iommu_iova_get_copy(iommu, &iova_copy);
2490 list_for_each_entry(domain, &iommu->domain_list, next) {
2491 group = find_iommu_group(domain, iommu_group);
2495 iommu_detach_group(domain->domain, group->iommu_group);
2496 update_dirty_scope = !group->pinned_page_dirty_scope;
2497 list_del(&group->next);
2500 * Group ownership provides privilege, if the group list is
2501 * empty, the domain goes away. If it's the last domain with
2502 * iommu and external domain doesn't exist, then all the
2503 * mappings go away too. If it's the last domain with iommu and
2504 * external domain exist, update accounting
2506 if (list_empty(&domain->group_list)) {
2507 if (list_is_singular(&iommu->domain_list)) {
2508 if (list_empty(&iommu->emulated_iommu_groups)) {
2509 WARN_ON(!list_empty(
2510 &iommu->device_list));
2511 vfio_iommu_unmap_unpin_all(iommu);
2513 vfio_iommu_unmap_unpin_reaccount(iommu);
2516 iommu_domain_free(domain->domain);
2517 list_del(&domain->next);
2519 vfio_iommu_aper_expand(iommu, &iova_copy);
2520 vfio_update_pgsize_bitmap(iommu);
2525 if (!vfio_iommu_resv_refresh(iommu, &iova_copy))
2526 vfio_iommu_iova_insert_copy(iommu, &iova_copy);
2528 vfio_iommu_iova_free(&iova_copy);
2532 * Removal of a group without dirty tracking may allow the iommu scope
2535 if (update_dirty_scope) {
2536 iommu->num_non_pinned_groups--;
2537 if (iommu->dirty_page_tracking)
2538 vfio_iommu_populate_bitmap_full(iommu);
2540 mutex_unlock(&iommu->lock);
2543 static void *vfio_iommu_type1_open(unsigned long arg)
2545 struct vfio_iommu *iommu;
2547 iommu = kzalloc(sizeof(*iommu), GFP_KERNEL);
2549 return ERR_PTR(-ENOMEM);
2552 case VFIO_TYPE1_IOMMU:
2554 case VFIO_TYPE1_NESTING_IOMMU:
2555 iommu->nesting = true;
2557 case VFIO_TYPE1v2_IOMMU:
2562 return ERR_PTR(-EINVAL);
2565 INIT_LIST_HEAD(&iommu->domain_list);
2566 INIT_LIST_HEAD(&iommu->iova_list);
2567 iommu->dma_list = RB_ROOT;
2568 iommu->dma_avail = dma_entry_limit;
2569 mutex_init(&iommu->lock);
2570 mutex_init(&iommu->device_list_lock);
2571 INIT_LIST_HEAD(&iommu->device_list);
2572 iommu->pgsize_bitmap = PAGE_MASK;
2573 INIT_LIST_HEAD(&iommu->emulated_iommu_groups);
2578 static void vfio_release_domain(struct vfio_domain *domain)
2580 struct vfio_iommu_group *group, *group_tmp;
2582 list_for_each_entry_safe(group, group_tmp,
2583 &domain->group_list, next) {
2584 iommu_detach_group(domain->domain, group->iommu_group);
2585 list_del(&group->next);
2589 iommu_domain_free(domain->domain);
2592 static void vfio_iommu_type1_release(void *iommu_data)
2594 struct vfio_iommu *iommu = iommu_data;
2595 struct vfio_domain *domain, *domain_tmp;
2596 struct vfio_iommu_group *group, *next_group;
2598 list_for_each_entry_safe(group, next_group,
2599 &iommu->emulated_iommu_groups, next) {
2600 list_del(&group->next);
2604 vfio_iommu_unmap_unpin_all(iommu);
2606 list_for_each_entry_safe(domain, domain_tmp,
2607 &iommu->domain_list, next) {
2608 vfio_release_domain(domain);
2609 list_del(&domain->next);
2613 vfio_iommu_iova_free(&iommu->iova_list);
2618 static int vfio_domains_have_enforce_cache_coherency(struct vfio_iommu *iommu)
2620 struct vfio_domain *domain;
2623 mutex_lock(&iommu->lock);
2624 list_for_each_entry(domain, &iommu->domain_list, next) {
2625 if (!(domain->enforce_cache_coherency)) {
2630 mutex_unlock(&iommu->lock);
2635 static bool vfio_iommu_has_emulated(struct vfio_iommu *iommu)
2639 mutex_lock(&iommu->lock);
2640 ret = !list_empty(&iommu->emulated_iommu_groups);
2641 mutex_unlock(&iommu->lock);
2645 static int vfio_iommu_type1_check_extension(struct vfio_iommu *iommu,
2649 case VFIO_TYPE1_IOMMU:
2650 case VFIO_TYPE1v2_IOMMU:
2651 case VFIO_TYPE1_NESTING_IOMMU:
2652 case VFIO_UNMAP_ALL:
2654 case VFIO_UPDATE_VADDR:
2656 * Disable this feature if mdevs are present. They cannot
2657 * safely pin/unpin/rw while vaddrs are being updated.
2659 return iommu && !vfio_iommu_has_emulated(iommu);
2660 case VFIO_DMA_CC_IOMMU:
2663 return vfio_domains_have_enforce_cache_coherency(iommu);
2669 static int vfio_iommu_iova_add_cap(struct vfio_info_cap *caps,
2670 struct vfio_iommu_type1_info_cap_iova_range *cap_iovas,
2673 struct vfio_info_cap_header *header;
2674 struct vfio_iommu_type1_info_cap_iova_range *iova_cap;
2676 header = vfio_info_cap_add(caps, size,
2677 VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE, 1);
2679 return PTR_ERR(header);
2681 iova_cap = container_of(header,
2682 struct vfio_iommu_type1_info_cap_iova_range,
2684 iova_cap->nr_iovas = cap_iovas->nr_iovas;
2685 memcpy(iova_cap->iova_ranges, cap_iovas->iova_ranges,
2686 cap_iovas->nr_iovas * sizeof(*cap_iovas->iova_ranges));
2690 static int vfio_iommu_iova_build_caps(struct vfio_iommu *iommu,
2691 struct vfio_info_cap *caps)
2693 struct vfio_iommu_type1_info_cap_iova_range *cap_iovas;
2694 struct vfio_iova *iova;
2696 int iovas = 0, i = 0, ret;
2698 list_for_each_entry(iova, &iommu->iova_list, list)
2703 * Return 0 as a container with a single mdev device
2704 * will have an empty list
2709 size = struct_size(cap_iovas, iova_ranges, iovas);
2711 cap_iovas = kzalloc(size, GFP_KERNEL);
2715 cap_iovas->nr_iovas = iovas;
2717 list_for_each_entry(iova, &iommu->iova_list, list) {
2718 cap_iovas->iova_ranges[i].start = iova->start;
2719 cap_iovas->iova_ranges[i].end = iova->end;
2723 ret = vfio_iommu_iova_add_cap(caps, cap_iovas, size);
2729 static int vfio_iommu_migration_build_caps(struct vfio_iommu *iommu,
2730 struct vfio_info_cap *caps)
2732 struct vfio_iommu_type1_info_cap_migration cap_mig;
2734 cap_mig.header.id = VFIO_IOMMU_TYPE1_INFO_CAP_MIGRATION;
2735 cap_mig.header.version = 1;
2738 /* support minimum pgsize */
2739 cap_mig.pgsize_bitmap = (size_t)1 << __ffs(iommu->pgsize_bitmap);
2740 cap_mig.max_dirty_bitmap_size = DIRTY_BITMAP_SIZE_MAX;
2742 return vfio_info_add_capability(caps, &cap_mig.header, sizeof(cap_mig));
2745 static int vfio_iommu_dma_avail_build_caps(struct vfio_iommu *iommu,
2746 struct vfio_info_cap *caps)
2748 struct vfio_iommu_type1_info_dma_avail cap_dma_avail;
2750 cap_dma_avail.header.id = VFIO_IOMMU_TYPE1_INFO_DMA_AVAIL;
2751 cap_dma_avail.header.version = 1;
2753 cap_dma_avail.avail = iommu->dma_avail;
2755 return vfio_info_add_capability(caps, &cap_dma_avail.header,
2756 sizeof(cap_dma_avail));
2759 static int vfio_iommu_type1_get_info(struct vfio_iommu *iommu,
2762 struct vfio_iommu_type1_info info;
2763 unsigned long minsz;
2764 struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
2765 unsigned long capsz;
2768 minsz = offsetofend(struct vfio_iommu_type1_info, iova_pgsizes);
2770 /* For backward compatibility, cannot require this */
2771 capsz = offsetofend(struct vfio_iommu_type1_info, cap_offset);
2773 if (copy_from_user(&info, (void __user *)arg, minsz))
2776 if (info.argsz < minsz)
2779 if (info.argsz >= capsz) {
2781 info.cap_offset = 0; /* output, no-recopy necessary */
2784 mutex_lock(&iommu->lock);
2785 info.flags = VFIO_IOMMU_INFO_PGSIZES;
2787 info.iova_pgsizes = iommu->pgsize_bitmap;
2789 ret = vfio_iommu_migration_build_caps(iommu, &caps);
2792 ret = vfio_iommu_dma_avail_build_caps(iommu, &caps);
2795 ret = vfio_iommu_iova_build_caps(iommu, &caps);
2797 mutex_unlock(&iommu->lock);
2803 info.flags |= VFIO_IOMMU_INFO_CAPS;
2805 if (info.argsz < sizeof(info) + caps.size) {
2806 info.argsz = sizeof(info) + caps.size;
2808 vfio_info_cap_shift(&caps, sizeof(info));
2809 if (copy_to_user((void __user *)arg +
2810 sizeof(info), caps.buf,
2815 info.cap_offset = sizeof(info);
2821 return copy_to_user((void __user *)arg, &info, minsz) ?
2825 static int vfio_iommu_type1_map_dma(struct vfio_iommu *iommu,
2828 struct vfio_iommu_type1_dma_map map;
2829 unsigned long minsz;
2830 uint32_t mask = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE |
2831 VFIO_DMA_MAP_FLAG_VADDR;
2833 minsz = offsetofend(struct vfio_iommu_type1_dma_map, size);
2835 if (copy_from_user(&map, (void __user *)arg, minsz))
2838 if (map.argsz < minsz || map.flags & ~mask)
2841 return vfio_dma_do_map(iommu, &map);
2844 static int vfio_iommu_type1_unmap_dma(struct vfio_iommu *iommu,
2847 struct vfio_iommu_type1_dma_unmap unmap;
2848 struct vfio_bitmap bitmap = { 0 };
2849 uint32_t mask = VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP |
2850 VFIO_DMA_UNMAP_FLAG_VADDR |
2851 VFIO_DMA_UNMAP_FLAG_ALL;
2852 unsigned long minsz;
2855 minsz = offsetofend(struct vfio_iommu_type1_dma_unmap, size);
2857 if (copy_from_user(&unmap, (void __user *)arg, minsz))
2860 if (unmap.argsz < minsz || unmap.flags & ~mask)
2863 if ((unmap.flags & VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP) &&
2864 (unmap.flags & (VFIO_DMA_UNMAP_FLAG_ALL |
2865 VFIO_DMA_UNMAP_FLAG_VADDR)))
2868 if (unmap.flags & VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP) {
2869 unsigned long pgshift;
2871 if (unmap.argsz < (minsz + sizeof(bitmap)))
2874 if (copy_from_user(&bitmap,
2875 (void __user *)(arg + minsz),
2879 if (!access_ok((void __user *)bitmap.data, bitmap.size))
2882 pgshift = __ffs(bitmap.pgsize);
2883 ret = verify_bitmap_size(unmap.size >> pgshift,
2889 ret = vfio_dma_do_unmap(iommu, &unmap, &bitmap);
2893 return copy_to_user((void __user *)arg, &unmap, minsz) ?
2897 static int vfio_iommu_type1_dirty_pages(struct vfio_iommu *iommu,
2900 struct vfio_iommu_type1_dirty_bitmap dirty;
2901 uint32_t mask = VFIO_IOMMU_DIRTY_PAGES_FLAG_START |
2902 VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP |
2903 VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
2904 unsigned long minsz;
2910 minsz = offsetofend(struct vfio_iommu_type1_dirty_bitmap, flags);
2912 if (copy_from_user(&dirty, (void __user *)arg, minsz))
2915 if (dirty.argsz < minsz || dirty.flags & ~mask)
2918 /* only one flag should be set at a time */
2919 if (__ffs(dirty.flags) != __fls(dirty.flags))
2922 if (dirty.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_START) {
2925 mutex_lock(&iommu->lock);
2926 pgsize = 1 << __ffs(iommu->pgsize_bitmap);
2927 if (!iommu->dirty_page_tracking) {
2928 ret = vfio_dma_bitmap_alloc_all(iommu, pgsize);
2930 iommu->dirty_page_tracking = true;
2932 mutex_unlock(&iommu->lock);
2934 } else if (dirty.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP) {
2935 mutex_lock(&iommu->lock);
2936 if (iommu->dirty_page_tracking) {
2937 iommu->dirty_page_tracking = false;
2938 vfio_dma_bitmap_free_all(iommu);
2940 mutex_unlock(&iommu->lock);
2942 } else if (dirty.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP) {
2943 struct vfio_iommu_type1_dirty_bitmap_get range;
2944 unsigned long pgshift;
2945 size_t data_size = dirty.argsz - minsz;
2946 size_t iommu_pgsize;
2948 if (!data_size || data_size < sizeof(range))
2951 if (copy_from_user(&range, (void __user *)(arg + minsz),
2955 if (range.iova + range.size < range.iova)
2957 if (!access_ok((void __user *)range.bitmap.data,
2961 pgshift = __ffs(range.bitmap.pgsize);
2962 ret = verify_bitmap_size(range.size >> pgshift,
2967 mutex_lock(&iommu->lock);
2969 iommu_pgsize = (size_t)1 << __ffs(iommu->pgsize_bitmap);
2971 /* allow only smallest supported pgsize */
2972 if (range.bitmap.pgsize != iommu_pgsize) {
2976 if (range.iova & (iommu_pgsize - 1)) {
2980 if (!range.size || range.size & (iommu_pgsize - 1)) {
2985 if (iommu->dirty_page_tracking)
2986 ret = vfio_iova_dirty_bitmap(range.bitmap.data,
2989 range.bitmap.pgsize);
2993 mutex_unlock(&iommu->lock);
3001 static long vfio_iommu_type1_ioctl(void *iommu_data,
3002 unsigned int cmd, unsigned long arg)
3004 struct vfio_iommu *iommu = iommu_data;
3007 case VFIO_CHECK_EXTENSION:
3008 return vfio_iommu_type1_check_extension(iommu, arg);
3009 case VFIO_IOMMU_GET_INFO:
3010 return vfio_iommu_type1_get_info(iommu, arg);
3011 case VFIO_IOMMU_MAP_DMA:
3012 return vfio_iommu_type1_map_dma(iommu, arg);
3013 case VFIO_IOMMU_UNMAP_DMA:
3014 return vfio_iommu_type1_unmap_dma(iommu, arg);
3015 case VFIO_IOMMU_DIRTY_PAGES:
3016 return vfio_iommu_type1_dirty_pages(iommu, arg);
3022 static void vfio_iommu_type1_register_device(void *iommu_data,
3023 struct vfio_device *vdev)
3025 struct vfio_iommu *iommu = iommu_data;
3027 if (!vdev->ops->dma_unmap)
3031 * list_empty(&iommu->device_list) is tested under the iommu->lock while
3032 * iteration for dma_unmap must be done under the device_list_lock.
3033 * Holding both locks here allows avoiding the device_list_lock in
3034 * several fast paths. See vfio_notify_dma_unmap()
3036 mutex_lock(&iommu->lock);
3037 mutex_lock(&iommu->device_list_lock);
3038 list_add(&vdev->iommu_entry, &iommu->device_list);
3039 mutex_unlock(&iommu->device_list_lock);
3040 mutex_unlock(&iommu->lock);
3043 static void vfio_iommu_type1_unregister_device(void *iommu_data,
3044 struct vfio_device *vdev)
3046 struct vfio_iommu *iommu = iommu_data;
3048 if (!vdev->ops->dma_unmap)
3051 mutex_lock(&iommu->lock);
3052 mutex_lock(&iommu->device_list_lock);
3053 list_del(&vdev->iommu_entry);
3054 mutex_unlock(&iommu->device_list_lock);
3055 mutex_unlock(&iommu->lock);
3058 static int vfio_iommu_type1_dma_rw_chunk(struct vfio_iommu *iommu,
3059 dma_addr_t user_iova, void *data,
3060 size_t count, bool write,
3063 struct mm_struct *mm;
3064 unsigned long vaddr;
3065 struct vfio_dma *dma;
3066 bool kthread = current->mm == NULL;
3071 dma = vfio_find_dma(iommu, user_iova, 1);
3075 if ((write && !(dma->prot & IOMMU_WRITE)) ||
3076 !(dma->prot & IOMMU_READ))
3080 if (!mmget_not_zero(mm))
3085 else if (current->mm != mm)
3088 offset = user_iova - dma->iova;
3090 if (count > dma->size - offset)
3091 count = dma->size - offset;
3093 vaddr = dma->vaddr + offset;
3096 *copied = copy_to_user((void __user *)vaddr, data,
3098 if (*copied && iommu->dirty_page_tracking) {
3099 unsigned long pgshift = __ffs(iommu->pgsize_bitmap);
3101 * Bitmap populated with the smallest supported page
3104 bitmap_set(dma->bitmap, offset >> pgshift,
3105 ((offset + *copied - 1) >> pgshift) -
3106 (offset >> pgshift) + 1);
3109 *copied = copy_from_user(data, (void __user *)vaddr,
3112 kthread_unuse_mm(mm);
3115 return *copied ? 0 : -EFAULT;
3118 static int vfio_iommu_type1_dma_rw(void *iommu_data, dma_addr_t user_iova,
3119 void *data, size_t count, bool write)
3121 struct vfio_iommu *iommu = iommu_data;
3125 mutex_lock(&iommu->lock);
3127 if (WARN_ONCE(iommu->vaddr_invalid_count,
3128 "vfio_dma_rw not allowed with VFIO_UPDATE_VADDR\n")) {
3134 ret = vfio_iommu_type1_dma_rw_chunk(iommu, user_iova, data,
3135 count, write, &done);
3145 mutex_unlock(&iommu->lock);
3149 static struct iommu_domain *
3150 vfio_iommu_type1_group_iommu_domain(void *iommu_data,
3151 struct iommu_group *iommu_group)
3153 struct iommu_domain *domain = ERR_PTR(-ENODEV);
3154 struct vfio_iommu *iommu = iommu_data;
3155 struct vfio_domain *d;
3157 if (!iommu || !iommu_group)
3158 return ERR_PTR(-EINVAL);
3160 mutex_lock(&iommu->lock);
3161 list_for_each_entry(d, &iommu->domain_list, next) {
3162 if (find_iommu_group(d, iommu_group)) {
3167 mutex_unlock(&iommu->lock);
3172 static const struct vfio_iommu_driver_ops vfio_iommu_driver_ops_type1 = {
3173 .name = "vfio-iommu-type1",
3174 .owner = THIS_MODULE,
3175 .open = vfio_iommu_type1_open,
3176 .release = vfio_iommu_type1_release,
3177 .ioctl = vfio_iommu_type1_ioctl,
3178 .attach_group = vfio_iommu_type1_attach_group,
3179 .detach_group = vfio_iommu_type1_detach_group,
3180 .pin_pages = vfio_iommu_type1_pin_pages,
3181 .unpin_pages = vfio_iommu_type1_unpin_pages,
3182 .register_device = vfio_iommu_type1_register_device,
3183 .unregister_device = vfio_iommu_type1_unregister_device,
3184 .dma_rw = vfio_iommu_type1_dma_rw,
3185 .group_iommu_domain = vfio_iommu_type1_group_iommu_domain,
3188 static int __init vfio_iommu_type1_init(void)
3190 return vfio_register_iommu_driver(&vfio_iommu_driver_ops_type1);
3193 static void __exit vfio_iommu_type1_cleanup(void)
3195 vfio_unregister_iommu_driver(&vfio_iommu_driver_ops_type1);
3198 module_init(vfio_iommu_type1_init);
3199 module_exit(vfio_iommu_type1_cleanup);
3201 MODULE_VERSION(DRIVER_VERSION);
3202 MODULE_LICENSE("GPL v2");
3203 MODULE_AUTHOR(DRIVER_AUTHOR);
3204 MODULE_DESCRIPTION(DRIVER_DESC);