2 * VFIO: IOMMU DMA mapping support for Type1 IOMMU
4 * Copyright (C) 2012 Red Hat, Inc. All rights reserved.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
11 * Derived from original vfio:
12 * Copyright 2010 Cisco Systems, Inc. All rights reserved.
15 * We arbitrarily define a Type1 IOMMU as one matching the below code.
16 * It could be called the x86 IOMMU as it's designed for AMD-Vi & Intel
17 * VT-d, but that makes it harder to re-use as theoretically anyone
18 * implementing a similar IOMMU could make use of this. We expect the
19 * IOMMU to support the IOMMU API and have few to no restrictions around
20 * the IOVA range that can be mapped. The Type1 IOMMU is currently
21 * optimized for relatively static mappings of a userspace process with
22 * userpsace pages pinned into memory. We also assume devices and IOMMU
23 * domains are PCI based as the IOMMU API is still centered around a
24 * device/bus interface rather than a group interface.
27 #include <linux/compat.h>
28 #include <linux/device.h>
30 #include <linux/iommu.h>
31 #include <linux/module.h>
33 #include <linux/rbtree.h>
34 #include <linux/sched.h>
35 #include <linux/slab.h>
36 #include <linux/uaccess.h>
37 #include <linux/vfio.h>
38 #include <linux/workqueue.h>
39 #include <linux/mdev.h>
40 #include <linux/notifier.h>
41 #include <linux/dma-iommu.h>
42 #include <linux/irqdomain.h>
44 #define DRIVER_VERSION "0.2"
46 #define DRIVER_DESC "Type1 IOMMU driver for VFIO"
48 static bool allow_unsafe_interrupts;
49 module_param_named(allow_unsafe_interrupts,
50 allow_unsafe_interrupts, bool, S_IRUGO | S_IWUSR);
51 MODULE_PARM_DESC(allow_unsafe_interrupts,
52 "Enable VFIO IOMMU support for on platforms without interrupt remapping support.");
54 static bool disable_hugepages;
55 module_param_named(disable_hugepages,
56 disable_hugepages, bool, S_IRUGO | S_IWUSR);
57 MODULE_PARM_DESC(disable_hugepages,
58 "Disable VFIO IOMMU support for IOMMU hugepages.");
61 struct list_head domain_list;
62 struct vfio_domain *external_domain; /* domain for external user */
64 struct rb_root dma_list;
65 struct blocking_notifier_head notifier;
71 struct iommu_domain *domain;
72 struct list_head next;
73 struct list_head group_list;
74 int prot; /* IOMMU_CACHE */
75 bool fgsp; /* Fine-grained super pages */
80 dma_addr_t iova; /* Device address */
81 unsigned long vaddr; /* Process virtual addr */
82 size_t size; /* Map size (bytes) */
83 int prot; /* IOMMU_READ/WRITE */
85 struct task_struct *task;
86 struct rb_root pfn_list; /* Ex-user pinned pfn list */
90 struct iommu_group *iommu_group;
91 struct list_head next;
95 * Guest RAM pinning working set or DMA target
99 dma_addr_t iova; /* Device address */
100 unsigned long pfn; /* Host pfn */
104 #define IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu) \
105 (!list_empty(&iommu->domain_list))
107 static int put_pfn(unsigned long pfn, int prot);
110 * This code handles mapping and unmapping of user data buffers
111 * into DMA'ble space using the IOMMU
114 static struct vfio_dma *vfio_find_dma(struct vfio_iommu *iommu,
115 dma_addr_t start, size_t size)
117 struct rb_node *node = iommu->dma_list.rb_node;
120 struct vfio_dma *dma = rb_entry(node, struct vfio_dma, node);
122 if (start + size <= dma->iova)
123 node = node->rb_left;
124 else if (start >= dma->iova + dma->size)
125 node = node->rb_right;
133 static void vfio_link_dma(struct vfio_iommu *iommu, struct vfio_dma *new)
135 struct rb_node **link = &iommu->dma_list.rb_node, *parent = NULL;
136 struct vfio_dma *dma;
140 dma = rb_entry(parent, struct vfio_dma, node);
142 if (new->iova + new->size <= dma->iova)
143 link = &(*link)->rb_left;
145 link = &(*link)->rb_right;
148 rb_link_node(&new->node, parent, link);
149 rb_insert_color(&new->node, &iommu->dma_list);
152 static void vfio_unlink_dma(struct vfio_iommu *iommu, struct vfio_dma *old)
154 rb_erase(&old->node, &iommu->dma_list);
158 * Helper Functions for host iova-pfn list
160 static struct vfio_pfn *vfio_find_vpfn(struct vfio_dma *dma, dma_addr_t iova)
162 struct vfio_pfn *vpfn;
163 struct rb_node *node = dma->pfn_list.rb_node;
166 vpfn = rb_entry(node, struct vfio_pfn, node);
168 if (iova < vpfn->iova)
169 node = node->rb_left;
170 else if (iova > vpfn->iova)
171 node = node->rb_right;
178 static void vfio_link_pfn(struct vfio_dma *dma,
179 struct vfio_pfn *new)
181 struct rb_node **link, *parent = NULL;
182 struct vfio_pfn *vpfn;
184 link = &dma->pfn_list.rb_node;
187 vpfn = rb_entry(parent, struct vfio_pfn, node);
189 if (new->iova < vpfn->iova)
190 link = &(*link)->rb_left;
192 link = &(*link)->rb_right;
195 rb_link_node(&new->node, parent, link);
196 rb_insert_color(&new->node, &dma->pfn_list);
199 static void vfio_unlink_pfn(struct vfio_dma *dma, struct vfio_pfn *old)
201 rb_erase(&old->node, &dma->pfn_list);
204 static int vfio_add_to_pfn_list(struct vfio_dma *dma, dma_addr_t iova,
207 struct vfio_pfn *vpfn;
209 vpfn = kzalloc(sizeof(*vpfn), GFP_KERNEL);
215 atomic_set(&vpfn->ref_count, 1);
216 vfio_link_pfn(dma, vpfn);
220 static void vfio_remove_from_pfn_list(struct vfio_dma *dma,
221 struct vfio_pfn *vpfn)
223 vfio_unlink_pfn(dma, vpfn);
227 static struct vfio_pfn *vfio_iova_get_vfio_pfn(struct vfio_dma *dma,
230 struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
233 atomic_inc(&vpfn->ref_count);
237 static int vfio_iova_put_vfio_pfn(struct vfio_dma *dma, struct vfio_pfn *vpfn)
241 if (atomic_dec_and_test(&vpfn->ref_count)) {
242 ret = put_pfn(vpfn->pfn, dma->prot);
243 vfio_remove_from_pfn_list(dma, vpfn);
249 struct mm_struct *mm;
251 struct work_struct work;
254 /* delayed decrement/increment for locked_vm */
255 static void vfio_lock_acct_bg(struct work_struct *work)
257 struct vwork *vwork = container_of(work, struct vwork, work);
258 struct mm_struct *mm;
261 down_write(&mm->mmap_sem);
262 mm->locked_vm += vwork->npage;
263 up_write(&mm->mmap_sem);
268 static void vfio_lock_acct(struct task_struct *task, long npage)
271 struct mm_struct *mm;
277 is_current = (task->mm == current->mm);
279 mm = is_current ? task->mm : get_task_mm(task);
281 return; /* process exited */
283 if (down_write_trylock(&mm->mmap_sem)) {
284 mm->locked_vm += npage;
285 up_write(&mm->mmap_sem);
292 mm = get_task_mm(task);
298 * Couldn't get mmap_sem lock, so must setup to update
299 * mm->locked_vm later. If locked_vm were atomic, we
300 * wouldn't need this silliness
302 vwork = kmalloc(sizeof(struct vwork), GFP_KERNEL);
303 if (WARN_ON(!vwork)) {
307 INIT_WORK(&vwork->work, vfio_lock_acct_bg);
309 vwork->npage = npage;
310 schedule_work(&vwork->work);
314 * Some mappings aren't backed by a struct page, for example an mmap'd
315 * MMIO range for our own or another device. These use a different
316 * pfn conversion and shouldn't be tracked as locked pages.
318 static bool is_invalid_reserved_pfn(unsigned long pfn)
320 if (pfn_valid(pfn)) {
322 struct page *tail = pfn_to_page(pfn);
323 struct page *head = compound_head(tail);
324 reserved = !!(PageReserved(head));
327 * "head" is not a dangling pointer
328 * (compound_head takes care of that)
329 * but the hugepage may have been split
330 * from under us (and we may not hold a
331 * reference count on the head page so it can
332 * be reused before we run PageReferenced), so
333 * we've to check PageTail before returning
340 return PageReserved(tail);
346 static int put_pfn(unsigned long pfn, int prot)
348 if (!is_invalid_reserved_pfn(pfn)) {
349 struct page *page = pfn_to_page(pfn);
350 if (prot & IOMMU_WRITE)
358 static int vaddr_get_pfn(struct mm_struct *mm, unsigned long vaddr,
359 int prot, unsigned long *pfn)
361 struct page *page[1];
362 struct vm_area_struct *vma;
365 if (mm == current->mm) {
366 ret = get_user_pages_fast(vaddr, 1, !!(prot & IOMMU_WRITE),
369 unsigned int flags = 0;
371 if (prot & IOMMU_WRITE)
374 down_read(&mm->mmap_sem);
375 ret = get_user_pages_remote(NULL, mm, vaddr, 1, flags, page,
377 up_read(&mm->mmap_sem);
381 *pfn = page_to_pfn(page[0]);
385 down_read(&mm->mmap_sem);
387 vma = find_vma_intersection(mm, vaddr, vaddr + 1);
389 if (vma && vma->vm_flags & VM_PFNMAP) {
390 *pfn = ((vaddr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
391 if (is_invalid_reserved_pfn(*pfn))
395 up_read(&mm->mmap_sem);
400 * Attempt to pin pages. We really don't want to track all the pfns and
401 * the iommu can only map chunks of consecutive pfns anyway, so get the
402 * first page and all consecutive pages with the same locking.
404 static long vfio_pin_pages_remote(struct vfio_dma *dma, unsigned long vaddr,
405 long npage, unsigned long *pfn_base)
407 unsigned long limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
408 bool lock_cap = capable(CAP_IPC_LOCK);
409 long ret, pinned = 0, lock_acct = 0;
411 dma_addr_t iova = vaddr - dma->vaddr + dma->iova;
413 /* This code path is only user initiated */
417 ret = vaddr_get_pfn(current->mm, vaddr, dma->prot, pfn_base);
422 rsvd = is_invalid_reserved_pfn(*pfn_base);
425 * Reserved pages aren't counted against the user, externally pinned
426 * pages are already counted against the user.
428 if (!rsvd && !vfio_find_vpfn(dma, iova)) {
429 if (!lock_cap && current->mm->locked_vm + 1 > limit) {
430 put_pfn(*pfn_base, dma->prot);
431 pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n", __func__,
432 limit << PAGE_SHIFT);
438 if (unlikely(disable_hugepages))
441 /* Lock all the consecutive pages from pfn_base */
442 for (vaddr += PAGE_SIZE, iova += PAGE_SIZE; pinned < npage;
443 pinned++, vaddr += PAGE_SIZE, iova += PAGE_SIZE) {
444 unsigned long pfn = 0;
446 ret = vaddr_get_pfn(current->mm, vaddr, dma->prot, &pfn);
450 if (pfn != *pfn_base + pinned ||
451 rsvd != is_invalid_reserved_pfn(pfn)) {
452 put_pfn(pfn, dma->prot);
456 if (!rsvd && !vfio_find_vpfn(dma, iova)) {
458 current->mm->locked_vm + lock_acct + 1 > limit) {
459 put_pfn(pfn, dma->prot);
460 pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n",
461 __func__, limit << PAGE_SHIFT);
469 vfio_lock_acct(current, lock_acct);
474 static long vfio_unpin_pages_remote(struct vfio_dma *dma, dma_addr_t iova,
475 unsigned long pfn, long npage,
478 long unlocked = 0, locked = 0;
481 for (i = 0; i < npage; i++, iova += PAGE_SIZE) {
482 if (put_pfn(pfn++, dma->prot)) {
484 if (vfio_find_vpfn(dma, iova))
490 vfio_lock_acct(dma->task, locked - unlocked);
495 static int vfio_pin_page_external(struct vfio_dma *dma, unsigned long vaddr,
496 unsigned long *pfn_base, bool do_accounting)
499 bool lock_cap = has_capability(dma->task, CAP_IPC_LOCK);
500 struct mm_struct *mm;
504 mm = get_task_mm(dma->task);
508 ret = vaddr_get_pfn(mm, vaddr, dma->prot, pfn_base);
512 rsvd = is_invalid_reserved_pfn(*pfn_base);
513 limit = task_rlimit(dma->task, RLIMIT_MEMLOCK) >> PAGE_SHIFT;
515 if (!rsvd && !lock_cap && mm->locked_vm + 1 > limit) {
516 put_pfn(*pfn_base, dma->prot);
517 pr_warn("%s: Task %s (%d) RLIMIT_MEMLOCK (%ld) exceeded\n",
518 __func__, dma->task->comm, task_pid_nr(dma->task),
519 limit << PAGE_SHIFT);
524 if (!rsvd && do_accounting)
525 vfio_lock_acct(dma->task, 1);
533 static int vfio_unpin_page_external(struct vfio_dma *dma, dma_addr_t iova,
537 struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
542 unlocked = vfio_iova_put_vfio_pfn(dma, vpfn);
545 vfio_lock_acct(dma->task, -unlocked);
550 static int vfio_iommu_type1_pin_pages(void *iommu_data,
551 unsigned long *user_pfn,
553 unsigned long *phys_pfn)
555 struct vfio_iommu *iommu = iommu_data;
557 unsigned long remote_vaddr;
558 struct vfio_dma *dma;
561 if (!iommu || !user_pfn || !phys_pfn)
564 /* Supported for v2 version only */
568 mutex_lock(&iommu->lock);
570 /* Fail if notifier list is empty */
571 if ((!iommu->external_domain) || (!iommu->notifier.head)) {
577 * If iommu capable domain exist in the container then all pages are
578 * already pinned and accounted. Accouting should be done if there is no
579 * iommu capable domain in the container.
581 do_accounting = !IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu);
583 for (i = 0; i < npage; i++) {
585 struct vfio_pfn *vpfn;
587 iova = user_pfn[i] << PAGE_SHIFT;
588 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
594 if ((dma->prot & prot) != prot) {
599 vpfn = vfio_iova_get_vfio_pfn(dma, iova);
601 phys_pfn[i] = vpfn->pfn;
605 remote_vaddr = dma->vaddr + iova - dma->iova;
606 ret = vfio_pin_page_external(dma, remote_vaddr, &phys_pfn[i],
613 ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
615 vfio_unpin_page_external(dma, iova, do_accounting);
625 for (j = 0; j < i; j++) {
628 iova = user_pfn[j] << PAGE_SHIFT;
629 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
630 vfio_unpin_page_external(dma, iova, do_accounting);
634 mutex_unlock(&iommu->lock);
638 static int vfio_iommu_type1_unpin_pages(void *iommu_data,
639 unsigned long *user_pfn,
642 struct vfio_iommu *iommu = iommu_data;
646 if (!iommu || !user_pfn)
649 /* Supported for v2 version only */
653 mutex_lock(&iommu->lock);
655 if (!iommu->external_domain) {
656 mutex_unlock(&iommu->lock);
660 do_accounting = !IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu);
661 for (i = 0; i < npage; i++) {
662 struct vfio_dma *dma;
665 iova = user_pfn[i] << PAGE_SHIFT;
666 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
669 vfio_unpin_page_external(dma, iova, do_accounting);
673 mutex_unlock(&iommu->lock);
674 return i > npage ? npage : (i > 0 ? i : -EINVAL);
677 static long vfio_unmap_unpin(struct vfio_iommu *iommu, struct vfio_dma *dma,
680 dma_addr_t iova = dma->iova, end = dma->iova + dma->size;
681 struct vfio_domain *domain, *d;
687 if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
691 * We use the IOMMU to track the physical addresses, otherwise we'd
692 * need a much more complicated tracking system. Unfortunately that
693 * means we need to use one of the iommu domains to figure out the
694 * pfns to unpin. The rest need to be unmapped in advance so we have
695 * no iommu translations remaining when the pages are unpinned.
697 domain = d = list_first_entry(&iommu->domain_list,
698 struct vfio_domain, next);
700 list_for_each_entry_continue(d, &iommu->domain_list, next) {
701 iommu_unmap(d->domain, dma->iova, dma->size);
706 size_t unmapped, len;
707 phys_addr_t phys, next;
709 phys = iommu_iova_to_phys(domain->domain, iova);
710 if (WARN_ON(!phys)) {
716 * To optimize for fewer iommu_unmap() calls, each of which
717 * may require hardware cache flushing, try to find the
718 * largest contiguous physical memory chunk to unmap.
720 for (len = PAGE_SIZE;
721 !domain->fgsp && iova + len < end; len += PAGE_SIZE) {
722 next = iommu_iova_to_phys(domain->domain, iova + len);
723 if (next != phys + len)
727 unmapped = iommu_unmap(domain->domain, iova, len);
728 if (WARN_ON(!unmapped))
731 unlocked += vfio_unpin_pages_remote(dma, iova,
733 unmapped >> PAGE_SHIFT,
740 dma->iommu_mapped = false;
742 vfio_lock_acct(dma->task, -unlocked);
748 static void vfio_remove_dma(struct vfio_iommu *iommu, struct vfio_dma *dma)
750 vfio_unmap_unpin(iommu, dma, true);
751 vfio_unlink_dma(iommu, dma);
752 put_task_struct(dma->task);
756 static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
758 struct vfio_domain *domain;
759 unsigned long bitmap = ULONG_MAX;
761 mutex_lock(&iommu->lock);
762 list_for_each_entry(domain, &iommu->domain_list, next)
763 bitmap &= domain->domain->pgsize_bitmap;
764 mutex_unlock(&iommu->lock);
767 * In case the IOMMU supports page sizes smaller than PAGE_SIZE
768 * we pretend PAGE_SIZE is supported and hide sub-PAGE_SIZE sizes.
769 * That way the user will be able to map/unmap buffers whose size/
770 * start address is aligned with PAGE_SIZE. Pinning code uses that
771 * granularity while iommu driver can use the sub-PAGE_SIZE size
774 if (bitmap & ~PAGE_MASK) {
782 static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
783 struct vfio_iommu_type1_dma_unmap *unmap)
786 struct vfio_dma *dma, *dma_last = NULL;
788 int ret = 0, retries = 0;
790 mask = ((uint64_t)1 << __ffs(vfio_pgsize_bitmap(iommu))) - 1;
792 if (unmap->iova & mask)
794 if (!unmap->size || unmap->size & mask)
797 WARN_ON(mask & PAGE_MASK);
799 mutex_lock(&iommu->lock);
802 * vfio-iommu-type1 (v1) - User mappings were coalesced together to
803 * avoid tracking individual mappings. This means that the granularity
804 * of the original mapping was lost and the user was allowed to attempt
805 * to unmap any range. Depending on the contiguousness of physical
806 * memory and page sizes supported by the IOMMU, arbitrary unmaps may
807 * or may not have worked. We only guaranteed unmap granularity
808 * matching the original mapping; even though it was untracked here,
809 * the original mappings are reflected in IOMMU mappings. This
810 * resulted in a couple unusual behaviors. First, if a range is not
811 * able to be unmapped, ex. a set of 4k pages that was mapped as a
812 * 2M hugepage into the IOMMU, the unmap ioctl returns success but with
813 * a zero sized unmap. Also, if an unmap request overlaps the first
814 * address of a hugepage, the IOMMU will unmap the entire hugepage.
815 * This also returns success and the returned unmap size reflects the
816 * actual size unmapped.
818 * We attempt to maintain compatibility with this "v1" interface, but
819 * we take control out of the hands of the IOMMU. Therefore, an unmap
820 * request offset from the beginning of the original mapping will
821 * return success with zero sized unmap. And an unmap request covering
822 * the first iova of mapping will unmap the entire range.
824 * The v2 version of this interface intends to be more deterministic.
825 * Unmap requests must fully cover previous mappings. Multiple
826 * mappings may still be unmaped by specifying large ranges, but there
827 * must not be any previous mappings bisected by the range. An error
828 * will be returned if these conditions are not met. The v2 interface
829 * will only return success and a size of zero if there were no
830 * mappings within the range.
833 dma = vfio_find_dma(iommu, unmap->iova, 1);
834 if (dma && dma->iova != unmap->iova) {
838 dma = vfio_find_dma(iommu, unmap->iova + unmap->size - 1, 0);
839 if (dma && dma->iova + dma->size != unmap->iova + unmap->size) {
845 while ((dma = vfio_find_dma(iommu, unmap->iova, unmap->size))) {
846 if (!iommu->v2 && unmap->iova > dma->iova)
849 * Task with same address space who mapped this iova range is
850 * allowed to unmap the iova range.
852 if (dma->task->mm != current->mm)
855 if (!RB_EMPTY_ROOT(&dma->pfn_list)) {
856 struct vfio_iommu_type1_dma_unmap nb_unmap;
858 if (dma_last == dma) {
859 BUG_ON(++retries > 10);
865 nb_unmap.iova = dma->iova;
866 nb_unmap.size = dma->size;
869 * Notify anyone (mdev vendor drivers) to invalidate and
870 * unmap iovas within the range we're about to unmap.
871 * Vendor drivers MUST unpin pages in response to an
874 mutex_unlock(&iommu->lock);
875 blocking_notifier_call_chain(&iommu->notifier,
876 VFIO_IOMMU_NOTIFY_DMA_UNMAP,
880 unmapped += dma->size;
881 vfio_remove_dma(iommu, dma);
885 mutex_unlock(&iommu->lock);
887 /* Report how much was unmapped */
888 unmap->size = unmapped;
894 * Turns out AMD IOMMU has a page table bug where it won't map large pages
895 * to a region that previously mapped smaller pages. This should be fixed
896 * soon, so this is just a temporary workaround to break mappings down into
897 * PAGE_SIZE. Better to map smaller pages than nothing.
899 static int map_try_harder(struct vfio_domain *domain, dma_addr_t iova,
900 unsigned long pfn, long npage, int prot)
905 for (i = 0; i < npage; i++, pfn++, iova += PAGE_SIZE) {
906 ret = iommu_map(domain->domain, iova,
907 (phys_addr_t)pfn << PAGE_SHIFT,
908 PAGE_SIZE, prot | domain->prot);
913 for (; i < npage && i > 0; i--, iova -= PAGE_SIZE)
914 iommu_unmap(domain->domain, iova, PAGE_SIZE);
919 static int vfio_iommu_map(struct vfio_iommu *iommu, dma_addr_t iova,
920 unsigned long pfn, long npage, int prot)
922 struct vfio_domain *d;
925 list_for_each_entry(d, &iommu->domain_list, next) {
926 ret = iommu_map(d->domain, iova, (phys_addr_t)pfn << PAGE_SHIFT,
927 npage << PAGE_SHIFT, prot | d->prot);
930 map_try_harder(d, iova, pfn, npage, prot))
940 list_for_each_entry_continue_reverse(d, &iommu->domain_list, next)
941 iommu_unmap(d->domain, iova, npage << PAGE_SHIFT);
946 static int vfio_pin_map_dma(struct vfio_iommu *iommu, struct vfio_dma *dma,
949 dma_addr_t iova = dma->iova;
950 unsigned long vaddr = dma->vaddr;
951 size_t size = map_size;
957 /* Pin a contiguous chunk of memory */
958 npage = vfio_pin_pages_remote(dma, vaddr + dma->size,
959 size >> PAGE_SHIFT, &pfn);
967 ret = vfio_iommu_map(iommu, iova + dma->size, pfn, npage,
970 vfio_unpin_pages_remote(dma, iova + dma->size, pfn,
975 size -= npage << PAGE_SHIFT;
976 dma->size += npage << PAGE_SHIFT;
979 dma->iommu_mapped = true;
982 vfio_remove_dma(iommu, dma);
987 static int vfio_dma_do_map(struct vfio_iommu *iommu,
988 struct vfio_iommu_type1_dma_map *map)
990 dma_addr_t iova = map->iova;
991 unsigned long vaddr = map->vaddr;
992 size_t size = map->size;
993 int ret = 0, prot = 0;
995 struct vfio_dma *dma;
997 /* Verify that none of our __u64 fields overflow */
998 if (map->size != size || map->vaddr != vaddr || map->iova != iova)
1001 mask = ((uint64_t)1 << __ffs(vfio_pgsize_bitmap(iommu))) - 1;
1003 WARN_ON(mask & PAGE_MASK);
1005 /* READ/WRITE from device perspective */
1006 if (map->flags & VFIO_DMA_MAP_FLAG_WRITE)
1007 prot |= IOMMU_WRITE;
1008 if (map->flags & VFIO_DMA_MAP_FLAG_READ)
1011 if (!prot || !size || (size | iova | vaddr) & mask)
1014 /* Don't allow IOVA or virtual address wrap */
1015 if (iova + size - 1 < iova || vaddr + size - 1 < vaddr)
1018 mutex_lock(&iommu->lock);
1020 if (vfio_find_dma(iommu, iova, size)) {
1025 dma = kzalloc(sizeof(*dma), GFP_KERNEL);
1034 get_task_struct(current);
1035 dma->task = current;
1036 dma->pfn_list = RB_ROOT;
1038 /* Insert zero-sized and grow as we map chunks of it */
1039 vfio_link_dma(iommu, dma);
1041 /* Don't pin and map if container doesn't contain IOMMU capable domain*/
1042 if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
1045 ret = vfio_pin_map_dma(iommu, dma, size);
1048 mutex_unlock(&iommu->lock);
1052 static int vfio_bus_type(struct device *dev, void *data)
1054 struct bus_type **bus = data;
1056 if (*bus && *bus != dev->bus)
1064 static int vfio_iommu_replay(struct vfio_iommu *iommu,
1065 struct vfio_domain *domain)
1067 struct vfio_domain *d;
1071 /* Arbitrarily pick the first domain in the list for lookups */
1072 d = list_first_entry(&iommu->domain_list, struct vfio_domain, next);
1073 n = rb_first(&iommu->dma_list);
1075 for (; n; n = rb_next(n)) {
1076 struct vfio_dma *dma;
1079 dma = rb_entry(n, struct vfio_dma, node);
1082 while (iova < dma->iova + dma->size) {
1086 if (dma->iommu_mapped) {
1090 phys = iommu_iova_to_phys(d->domain, iova);
1092 if (WARN_ON(!phys)) {
1100 while (i < dma->iova + dma->size &&
1101 p == iommu_iova_to_phys(d->domain, i)) {
1108 unsigned long vaddr = dma->vaddr +
1110 size_t n = dma->iova + dma->size - iova;
1113 npage = vfio_pin_pages_remote(dma, vaddr,
1122 phys = pfn << PAGE_SHIFT;
1123 size = npage << PAGE_SHIFT;
1126 ret = iommu_map(domain->domain, iova, phys,
1127 size, dma->prot | domain->prot);
1133 dma->iommu_mapped = true;
1139 * We change our unmap behavior slightly depending on whether the IOMMU
1140 * supports fine-grained superpages. IOMMUs like AMD-Vi will use a superpage
1141 * for practically any contiguous power-of-two mapping we give it. This means
1142 * we don't need to look for contiguous chunks ourselves to make unmapping
1143 * more efficient. On IOMMUs with coarse-grained super pages, like Intel VT-d
1144 * with discrete 2M/1G/512G/1T superpages, identifying contiguous chunks
1145 * significantly boosts non-hugetlbfs mappings and doesn't seem to hurt when
1146 * hugetlbfs is in use.
1148 static void vfio_test_domain_fgsp(struct vfio_domain *domain)
1151 int ret, order = get_order(PAGE_SIZE * 2);
1153 pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, order);
1157 ret = iommu_map(domain->domain, 0, page_to_phys(pages), PAGE_SIZE * 2,
1158 IOMMU_READ | IOMMU_WRITE | domain->prot);
1160 size_t unmapped = iommu_unmap(domain->domain, 0, PAGE_SIZE);
1162 if (unmapped == PAGE_SIZE)
1163 iommu_unmap(domain->domain, PAGE_SIZE, PAGE_SIZE);
1165 domain->fgsp = true;
1168 __free_pages(pages, order);
1171 static struct vfio_group *find_iommu_group(struct vfio_domain *domain,
1172 struct iommu_group *iommu_group)
1174 struct vfio_group *g;
1176 list_for_each_entry(g, &domain->group_list, next) {
1177 if (g->iommu_group == iommu_group)
1184 static bool vfio_iommu_has_resv_msi(struct iommu_group *group,
1187 struct list_head group_resv_regions;
1188 struct iommu_resv_region *region, *next;
1191 INIT_LIST_HEAD(&group_resv_regions);
1192 iommu_get_group_resv_regions(group, &group_resv_regions);
1193 list_for_each_entry(region, &group_resv_regions, list) {
1194 if (region->type & IOMMU_RESV_MSI) {
1195 *base = region->start;
1201 list_for_each_entry_safe(region, next, &group_resv_regions, list)
1206 static int vfio_iommu_type1_attach_group(void *iommu_data,
1207 struct iommu_group *iommu_group)
1209 struct vfio_iommu *iommu = iommu_data;
1210 struct vfio_group *group;
1211 struct vfio_domain *domain, *d;
1212 struct bus_type *bus = NULL, *mdev_bus;
1214 bool resv_msi, msi_remap;
1215 phys_addr_t resv_msi_base;
1217 mutex_lock(&iommu->lock);
1219 list_for_each_entry(d, &iommu->domain_list, next) {
1220 if (find_iommu_group(d, iommu_group)) {
1221 mutex_unlock(&iommu->lock);
1226 if (iommu->external_domain) {
1227 if (find_iommu_group(iommu->external_domain, iommu_group)) {
1228 mutex_unlock(&iommu->lock);
1233 group = kzalloc(sizeof(*group), GFP_KERNEL);
1234 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
1235 if (!group || !domain) {
1240 group->iommu_group = iommu_group;
1242 /* Determine bus_type in order to allocate a domain */
1243 ret = iommu_group_for_each_dev(iommu_group, &bus, vfio_bus_type);
1247 mdev_bus = symbol_get(mdev_bus_type);
1250 if ((bus == mdev_bus) && !iommu_present(bus)) {
1251 symbol_put(mdev_bus_type);
1252 if (!iommu->external_domain) {
1253 INIT_LIST_HEAD(&domain->group_list);
1254 iommu->external_domain = domain;
1258 list_add(&group->next,
1259 &iommu->external_domain->group_list);
1260 mutex_unlock(&iommu->lock);
1263 symbol_put(mdev_bus_type);
1266 domain->domain = iommu_domain_alloc(bus);
1267 if (!domain->domain) {
1272 if (iommu->nesting) {
1275 ret = iommu_domain_set_attr(domain->domain, DOMAIN_ATTR_NESTING,
1281 ret = iommu_attach_group(domain->domain, iommu_group);
1285 resv_msi = vfio_iommu_has_resv_msi(iommu_group, &resv_msi_base);
1287 INIT_LIST_HEAD(&domain->group_list);
1288 list_add(&group->next, &domain->group_list);
1290 msi_remap = resv_msi ? irq_domain_check_msi_remap() :
1291 iommu_capable(bus, IOMMU_CAP_INTR_REMAP);
1293 if (!allow_unsafe_interrupts && !msi_remap) {
1294 pr_warn("%s: No interrupt remapping support. Use the module param \"allow_unsafe_interrupts\" to enable VFIO IOMMU support on this platform\n",
1300 if (iommu_capable(bus, IOMMU_CAP_CACHE_COHERENCY))
1301 domain->prot |= IOMMU_CACHE;
1304 * Try to match an existing compatible domain. We don't want to
1305 * preclude an IOMMU driver supporting multiple bus_types and being
1306 * able to include different bus_types in the same IOMMU domain, so
1307 * we test whether the domains use the same iommu_ops rather than
1308 * testing if they're on the same bus_type.
1310 list_for_each_entry(d, &iommu->domain_list, next) {
1311 if (d->domain->ops == domain->domain->ops &&
1312 d->prot == domain->prot) {
1313 iommu_detach_group(domain->domain, iommu_group);
1314 if (!iommu_attach_group(d->domain, iommu_group)) {
1315 list_add(&group->next, &d->group_list);
1316 iommu_domain_free(domain->domain);
1318 mutex_unlock(&iommu->lock);
1322 ret = iommu_attach_group(domain->domain, iommu_group);
1328 vfio_test_domain_fgsp(domain);
1330 /* replay mappings on new domains */
1331 ret = vfio_iommu_replay(iommu, domain);
1336 ret = iommu_get_msi_cookie(domain->domain, resv_msi_base);
1341 list_add(&domain->next, &iommu->domain_list);
1343 mutex_unlock(&iommu->lock);
1348 iommu_detach_group(domain->domain, iommu_group);
1350 iommu_domain_free(domain->domain);
1354 mutex_unlock(&iommu->lock);
1358 static void vfio_iommu_unmap_unpin_all(struct vfio_iommu *iommu)
1360 struct rb_node *node;
1362 while ((node = rb_first(&iommu->dma_list)))
1363 vfio_remove_dma(iommu, rb_entry(node, struct vfio_dma, node));
1366 static void vfio_iommu_unmap_unpin_reaccount(struct vfio_iommu *iommu)
1368 struct rb_node *n, *p;
1370 n = rb_first(&iommu->dma_list);
1371 for (; n; n = rb_next(n)) {
1372 struct vfio_dma *dma;
1373 long locked = 0, unlocked = 0;
1375 dma = rb_entry(n, struct vfio_dma, node);
1376 unlocked += vfio_unmap_unpin(iommu, dma, false);
1377 p = rb_first(&dma->pfn_list);
1378 for (; p; p = rb_next(p)) {
1379 struct vfio_pfn *vpfn = rb_entry(p, struct vfio_pfn,
1382 if (!is_invalid_reserved_pfn(vpfn->pfn))
1385 vfio_lock_acct(dma->task, locked - unlocked);
1389 static void vfio_sanity_check_pfn_list(struct vfio_iommu *iommu)
1393 n = rb_first(&iommu->dma_list);
1394 for (; n; n = rb_next(n)) {
1395 struct vfio_dma *dma;
1397 dma = rb_entry(n, struct vfio_dma, node);
1399 if (WARN_ON(!RB_EMPTY_ROOT(&dma->pfn_list)))
1402 /* mdev vendor driver must unregister notifier */
1403 WARN_ON(iommu->notifier.head);
1406 static void vfio_iommu_type1_detach_group(void *iommu_data,
1407 struct iommu_group *iommu_group)
1409 struct vfio_iommu *iommu = iommu_data;
1410 struct vfio_domain *domain;
1411 struct vfio_group *group;
1413 mutex_lock(&iommu->lock);
1415 if (iommu->external_domain) {
1416 group = find_iommu_group(iommu->external_domain, iommu_group);
1418 list_del(&group->next);
1421 if (list_empty(&iommu->external_domain->group_list)) {
1422 vfio_sanity_check_pfn_list(iommu);
1424 if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
1425 vfio_iommu_unmap_unpin_all(iommu);
1427 kfree(iommu->external_domain);
1428 iommu->external_domain = NULL;
1430 goto detach_group_done;
1434 list_for_each_entry(domain, &iommu->domain_list, next) {
1435 group = find_iommu_group(domain, iommu_group);
1439 iommu_detach_group(domain->domain, iommu_group);
1440 list_del(&group->next);
1443 * Group ownership provides privilege, if the group list is
1444 * empty, the domain goes away. If it's the last domain with
1445 * iommu and external domain doesn't exist, then all the
1446 * mappings go away too. If it's the last domain with iommu and
1447 * external domain exist, update accounting
1449 if (list_empty(&domain->group_list)) {
1450 if (list_is_singular(&iommu->domain_list)) {
1451 if (!iommu->external_domain)
1452 vfio_iommu_unmap_unpin_all(iommu);
1454 vfio_iommu_unmap_unpin_reaccount(iommu);
1456 iommu_domain_free(domain->domain);
1457 list_del(&domain->next);
1464 mutex_unlock(&iommu->lock);
1467 static void *vfio_iommu_type1_open(unsigned long arg)
1469 struct vfio_iommu *iommu;
1471 iommu = kzalloc(sizeof(*iommu), GFP_KERNEL);
1473 return ERR_PTR(-ENOMEM);
1476 case VFIO_TYPE1_IOMMU:
1478 case VFIO_TYPE1_NESTING_IOMMU:
1479 iommu->nesting = true;
1480 case VFIO_TYPE1v2_IOMMU:
1485 return ERR_PTR(-EINVAL);
1488 INIT_LIST_HEAD(&iommu->domain_list);
1489 iommu->dma_list = RB_ROOT;
1490 mutex_init(&iommu->lock);
1491 BLOCKING_INIT_NOTIFIER_HEAD(&iommu->notifier);
1496 static void vfio_release_domain(struct vfio_domain *domain, bool external)
1498 struct vfio_group *group, *group_tmp;
1500 list_for_each_entry_safe(group, group_tmp,
1501 &domain->group_list, next) {
1503 iommu_detach_group(domain->domain, group->iommu_group);
1504 list_del(&group->next);
1509 iommu_domain_free(domain->domain);
1512 static void vfio_iommu_type1_release(void *iommu_data)
1514 struct vfio_iommu *iommu = iommu_data;
1515 struct vfio_domain *domain, *domain_tmp;
1517 if (iommu->external_domain) {
1518 vfio_release_domain(iommu->external_domain, true);
1519 vfio_sanity_check_pfn_list(iommu);
1520 kfree(iommu->external_domain);
1523 vfio_iommu_unmap_unpin_all(iommu);
1525 list_for_each_entry_safe(domain, domain_tmp,
1526 &iommu->domain_list, next) {
1527 vfio_release_domain(domain, false);
1528 list_del(&domain->next);
1534 static int vfio_domains_have_iommu_cache(struct vfio_iommu *iommu)
1536 struct vfio_domain *domain;
1539 mutex_lock(&iommu->lock);
1540 list_for_each_entry(domain, &iommu->domain_list, next) {
1541 if (!(domain->prot & IOMMU_CACHE)) {
1546 mutex_unlock(&iommu->lock);
1551 static long vfio_iommu_type1_ioctl(void *iommu_data,
1552 unsigned int cmd, unsigned long arg)
1554 struct vfio_iommu *iommu = iommu_data;
1555 unsigned long minsz;
1557 if (cmd == VFIO_CHECK_EXTENSION) {
1559 case VFIO_TYPE1_IOMMU:
1560 case VFIO_TYPE1v2_IOMMU:
1561 case VFIO_TYPE1_NESTING_IOMMU:
1563 case VFIO_DMA_CC_IOMMU:
1566 return vfio_domains_have_iommu_cache(iommu);
1570 } else if (cmd == VFIO_IOMMU_GET_INFO) {
1571 struct vfio_iommu_type1_info info;
1573 minsz = offsetofend(struct vfio_iommu_type1_info, iova_pgsizes);
1575 if (copy_from_user(&info, (void __user *)arg, minsz))
1578 if (info.argsz < minsz)
1581 info.flags = VFIO_IOMMU_INFO_PGSIZES;
1583 info.iova_pgsizes = vfio_pgsize_bitmap(iommu);
1585 return copy_to_user((void __user *)arg, &info, minsz) ?
1588 } else if (cmd == VFIO_IOMMU_MAP_DMA) {
1589 struct vfio_iommu_type1_dma_map map;
1590 uint32_t mask = VFIO_DMA_MAP_FLAG_READ |
1591 VFIO_DMA_MAP_FLAG_WRITE;
1593 minsz = offsetofend(struct vfio_iommu_type1_dma_map, size);
1595 if (copy_from_user(&map, (void __user *)arg, minsz))
1598 if (map.argsz < minsz || map.flags & ~mask)
1601 return vfio_dma_do_map(iommu, &map);
1603 } else if (cmd == VFIO_IOMMU_UNMAP_DMA) {
1604 struct vfio_iommu_type1_dma_unmap unmap;
1607 minsz = offsetofend(struct vfio_iommu_type1_dma_unmap, size);
1609 if (copy_from_user(&unmap, (void __user *)arg, minsz))
1612 if (unmap.argsz < minsz || unmap.flags)
1615 ret = vfio_dma_do_unmap(iommu, &unmap);
1619 return copy_to_user((void __user *)arg, &unmap, minsz) ?
1626 static int vfio_iommu_type1_register_notifier(void *iommu_data,
1627 unsigned long *events,
1628 struct notifier_block *nb)
1630 struct vfio_iommu *iommu = iommu_data;
1632 /* clear known events */
1633 *events &= ~VFIO_IOMMU_NOTIFY_DMA_UNMAP;
1635 /* refuse to register if still events remaining */
1639 return blocking_notifier_chain_register(&iommu->notifier, nb);
1642 static int vfio_iommu_type1_unregister_notifier(void *iommu_data,
1643 struct notifier_block *nb)
1645 struct vfio_iommu *iommu = iommu_data;
1647 return blocking_notifier_chain_unregister(&iommu->notifier, nb);
1650 static const struct vfio_iommu_driver_ops vfio_iommu_driver_ops_type1 = {
1651 .name = "vfio-iommu-type1",
1652 .owner = THIS_MODULE,
1653 .open = vfio_iommu_type1_open,
1654 .release = vfio_iommu_type1_release,
1655 .ioctl = vfio_iommu_type1_ioctl,
1656 .attach_group = vfio_iommu_type1_attach_group,
1657 .detach_group = vfio_iommu_type1_detach_group,
1658 .pin_pages = vfio_iommu_type1_pin_pages,
1659 .unpin_pages = vfio_iommu_type1_unpin_pages,
1660 .register_notifier = vfio_iommu_type1_register_notifier,
1661 .unregister_notifier = vfio_iommu_type1_unregister_notifier,
1664 static int __init vfio_iommu_type1_init(void)
1666 return vfio_register_iommu_driver(&vfio_iommu_driver_ops_type1);
1669 static void __exit vfio_iommu_type1_cleanup(void)
1671 vfio_unregister_iommu_driver(&vfio_iommu_driver_ops_type1);
1674 module_init(vfio_iommu_type1_init);
1675 module_exit(vfio_iommu_type1_cleanup);
1677 MODULE_VERSION(DRIVER_VERSION);
1678 MODULE_LICENSE("GPL v2");
1679 MODULE_AUTHOR(DRIVER_AUTHOR);
1680 MODULE_DESCRIPTION(DRIVER_DESC);