1 // SPDX-License-Identifier: GPL-2.0-only
3 * A fairly generic DMA-API to IOMMU-API glue layer.
5 * Copyright (C) 2014-2015 ARM Ltd.
7 * based in part on arch/arm/mm/dma-mapping.c:
8 * Copyright (C) 2000-2004 Russell King
11 #include <linux/acpi_iort.h>
12 #include <linux/atomic.h>
13 #include <linux/crash_dump.h>
14 #include <linux/device.h>
15 #include <linux/dma-direct.h>
16 #include <linux/dma-map-ops.h>
17 #include <linux/gfp.h>
18 #include <linux/huge_mm.h>
19 #include <linux/iommu.h>
20 #include <linux/iova.h>
21 #include <linux/irq.h>
22 #include <linux/list_sort.h>
23 #include <linux/memremap.h>
25 #include <linux/mutex.h>
26 #include <linux/of_iommu.h>
27 #include <linux/pci.h>
28 #include <linux/scatterlist.h>
29 #include <linux/spinlock.h>
30 #include <linux/swiotlb.h>
31 #include <linux/vmalloc.h>
32 #include <trace/events/swiotlb.h>
34 #include "dma-iommu.h"
36 struct iommu_dma_msi_page {
37 struct list_head list;
42 enum iommu_dma_cookie_type {
43 IOMMU_DMA_IOVA_COOKIE,
47 struct iommu_dma_cookie {
48 enum iommu_dma_cookie_type type;
50 /* Full allocator for IOMMU_DMA_IOVA_COOKIE */
52 struct iova_domain iovad;
54 struct iova_fq __percpu *fq; /* Flush queue */
55 /* Number of TLB flushes that have been started */
56 atomic64_t fq_flush_start_cnt;
57 /* Number of TLB flushes that have been finished */
58 atomic64_t fq_flush_finish_cnt;
59 /* Timer to regularily empty the flush queues */
60 struct timer_list fq_timer;
61 /* 1 when timer is active, 0 when not */
64 /* Trivial linear page allocator for IOMMU_DMA_MSI_COOKIE */
67 struct list_head msi_page_list;
69 /* Domain for flush queue callback; NULL if flush queue not in use */
70 struct iommu_domain *fq_domain;
74 static DEFINE_STATIC_KEY_FALSE(iommu_deferred_attach_enabled);
75 bool iommu_dma_forcedac __read_mostly;
77 static int __init iommu_dma_forcedac_setup(char *str)
79 int ret = kstrtobool(str, &iommu_dma_forcedac);
81 if (!ret && iommu_dma_forcedac)
82 pr_info("Forcing DAC for PCI devices\n");
85 early_param("iommu.forcedac", iommu_dma_forcedac_setup);
87 /* Number of entries per flush queue */
88 #define IOVA_FQ_SIZE 256
90 /* Timeout (in ms) after which entries are flushed from the queue */
91 #define IOVA_FQ_TIMEOUT 10
93 /* Flush queue entry for deferred flushing */
94 struct iova_fq_entry {
95 unsigned long iova_pfn;
97 struct list_head freelist;
98 u64 counter; /* Flush counter when this entry was added */
101 /* Per-CPU flush queue structure */
103 struct iova_fq_entry entries[IOVA_FQ_SIZE];
104 unsigned int head, tail;
108 #define fq_ring_for_each(i, fq) \
109 for ((i) = (fq)->head; (i) != (fq)->tail; (i) = ((i) + 1) % IOVA_FQ_SIZE)
111 static inline bool fq_full(struct iova_fq *fq)
113 assert_spin_locked(&fq->lock);
114 return (((fq->tail + 1) % IOVA_FQ_SIZE) == fq->head);
117 static inline unsigned int fq_ring_add(struct iova_fq *fq)
119 unsigned int idx = fq->tail;
121 assert_spin_locked(&fq->lock);
123 fq->tail = (idx + 1) % IOVA_FQ_SIZE;
128 static void fq_ring_free(struct iommu_dma_cookie *cookie, struct iova_fq *fq)
130 u64 counter = atomic64_read(&cookie->fq_flush_finish_cnt);
133 assert_spin_locked(&fq->lock);
135 fq_ring_for_each(idx, fq) {
137 if (fq->entries[idx].counter >= counter)
140 put_pages_list(&fq->entries[idx].freelist);
141 free_iova_fast(&cookie->iovad,
142 fq->entries[idx].iova_pfn,
143 fq->entries[idx].pages);
145 fq->head = (fq->head + 1) % IOVA_FQ_SIZE;
149 static void fq_flush_iotlb(struct iommu_dma_cookie *cookie)
151 atomic64_inc(&cookie->fq_flush_start_cnt);
152 cookie->fq_domain->ops->flush_iotlb_all(cookie->fq_domain);
153 atomic64_inc(&cookie->fq_flush_finish_cnt);
156 static void fq_flush_timeout(struct timer_list *t)
158 struct iommu_dma_cookie *cookie = from_timer(cookie, t, fq_timer);
161 atomic_set(&cookie->fq_timer_on, 0);
162 fq_flush_iotlb(cookie);
164 for_each_possible_cpu(cpu) {
168 fq = per_cpu_ptr(cookie->fq, cpu);
169 spin_lock_irqsave(&fq->lock, flags);
170 fq_ring_free(cookie, fq);
171 spin_unlock_irqrestore(&fq->lock, flags);
175 static void queue_iova(struct iommu_dma_cookie *cookie,
176 unsigned long pfn, unsigned long pages,
177 struct list_head *freelist)
184 * Order against the IOMMU driver's pagetable update from unmapping
185 * @pte, to guarantee that fq_flush_iotlb() observes that if called
186 * from a different CPU before we release the lock below. Full barrier
187 * so it also pairs with iommu_dma_init_fq() to avoid seeing partially
188 * written fq state here.
192 fq = raw_cpu_ptr(cookie->fq);
193 spin_lock_irqsave(&fq->lock, flags);
196 * First remove all entries from the flush queue that have already been
197 * flushed out on another CPU. This makes the fq_full() check below less
200 fq_ring_free(cookie, fq);
203 fq_flush_iotlb(cookie);
204 fq_ring_free(cookie, fq);
207 idx = fq_ring_add(fq);
209 fq->entries[idx].iova_pfn = pfn;
210 fq->entries[idx].pages = pages;
211 fq->entries[idx].counter = atomic64_read(&cookie->fq_flush_start_cnt);
212 list_splice(freelist, &fq->entries[idx].freelist);
214 spin_unlock_irqrestore(&fq->lock, flags);
216 /* Avoid false sharing as much as possible. */
217 if (!atomic_read(&cookie->fq_timer_on) &&
218 !atomic_xchg(&cookie->fq_timer_on, 1))
219 mod_timer(&cookie->fq_timer,
220 jiffies + msecs_to_jiffies(IOVA_FQ_TIMEOUT));
223 static void iommu_dma_free_fq(struct iommu_dma_cookie *cookie)
230 del_timer_sync(&cookie->fq_timer);
231 /* The IOVAs will be torn down separately, so just free our queued pages */
232 for_each_possible_cpu(cpu) {
233 struct iova_fq *fq = per_cpu_ptr(cookie->fq, cpu);
235 fq_ring_for_each(idx, fq)
236 put_pages_list(&fq->entries[idx].freelist);
239 free_percpu(cookie->fq);
242 /* sysfs updates are serialised by the mutex of the group owning @domain */
243 int iommu_dma_init_fq(struct iommu_domain *domain)
245 struct iommu_dma_cookie *cookie = domain->iova_cookie;
246 struct iova_fq __percpu *queue;
249 if (cookie->fq_domain)
252 atomic64_set(&cookie->fq_flush_start_cnt, 0);
253 atomic64_set(&cookie->fq_flush_finish_cnt, 0);
255 queue = alloc_percpu(struct iova_fq);
257 pr_warn("iova flush queue initialization failed\n");
261 for_each_possible_cpu(cpu) {
262 struct iova_fq *fq = per_cpu_ptr(queue, cpu);
267 spin_lock_init(&fq->lock);
269 for (i = 0; i < IOVA_FQ_SIZE; i++)
270 INIT_LIST_HEAD(&fq->entries[i].freelist);
275 timer_setup(&cookie->fq_timer, fq_flush_timeout, 0);
276 atomic_set(&cookie->fq_timer_on, 0);
278 * Prevent incomplete fq state being observable. Pairs with path from
279 * __iommu_dma_unmap() through iommu_dma_free_iova() to queue_iova()
282 WRITE_ONCE(cookie->fq_domain, domain);
286 static inline size_t cookie_msi_granule(struct iommu_dma_cookie *cookie)
288 if (cookie->type == IOMMU_DMA_IOVA_COOKIE)
289 return cookie->iovad.granule;
293 static struct iommu_dma_cookie *cookie_alloc(enum iommu_dma_cookie_type type)
295 struct iommu_dma_cookie *cookie;
297 cookie = kzalloc(sizeof(*cookie), GFP_KERNEL);
299 INIT_LIST_HEAD(&cookie->msi_page_list);
306 * iommu_get_dma_cookie - Acquire DMA-API resources for a domain
307 * @domain: IOMMU domain to prepare for DMA-API usage
309 int iommu_get_dma_cookie(struct iommu_domain *domain)
311 if (domain->iova_cookie)
314 domain->iova_cookie = cookie_alloc(IOMMU_DMA_IOVA_COOKIE);
315 if (!domain->iova_cookie)
318 mutex_init(&domain->iova_cookie->mutex);
323 * iommu_get_msi_cookie - Acquire just MSI remapping resources
324 * @domain: IOMMU domain to prepare
325 * @base: Start address of IOVA region for MSI mappings
327 * Users who manage their own IOVA allocation and do not want DMA API support,
328 * but would still like to take advantage of automatic MSI remapping, can use
329 * this to initialise their own domain appropriately. Users should reserve a
330 * contiguous IOVA region, starting at @base, large enough to accommodate the
331 * number of PAGE_SIZE mappings necessary to cover every MSI doorbell address
332 * used by the devices attached to @domain.
334 int iommu_get_msi_cookie(struct iommu_domain *domain, dma_addr_t base)
336 struct iommu_dma_cookie *cookie;
338 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
341 if (domain->iova_cookie)
344 cookie = cookie_alloc(IOMMU_DMA_MSI_COOKIE);
348 cookie->msi_iova = base;
349 domain->iova_cookie = cookie;
352 EXPORT_SYMBOL(iommu_get_msi_cookie);
355 * iommu_put_dma_cookie - Release a domain's DMA mapping resources
356 * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie() or
357 * iommu_get_msi_cookie()
359 void iommu_put_dma_cookie(struct iommu_domain *domain)
361 struct iommu_dma_cookie *cookie = domain->iova_cookie;
362 struct iommu_dma_msi_page *msi, *tmp;
367 if (cookie->type == IOMMU_DMA_IOVA_COOKIE && cookie->iovad.granule) {
368 iommu_dma_free_fq(cookie);
369 put_iova_domain(&cookie->iovad);
372 list_for_each_entry_safe(msi, tmp, &cookie->msi_page_list, list) {
373 list_del(&msi->list);
377 domain->iova_cookie = NULL;
381 * iommu_dma_get_resv_regions - Reserved region driver helper
382 * @dev: Device from iommu_get_resv_regions()
383 * @list: Reserved region list from iommu_get_resv_regions()
385 * IOMMU drivers can use this to implement their .get_resv_regions callback
386 * for general non-IOMMU-specific reservations. Currently, this covers GICv3
387 * ITS region reservation on ACPI based ARM platforms that may require HW MSI
390 void iommu_dma_get_resv_regions(struct device *dev, struct list_head *list)
393 if (!is_of_node(dev_iommu_fwspec_get(dev)->iommu_fwnode))
394 iort_iommu_get_resv_regions(dev, list);
397 of_iommu_get_resv_regions(dev, list);
399 EXPORT_SYMBOL(iommu_dma_get_resv_regions);
401 static int cookie_init_hw_msi_region(struct iommu_dma_cookie *cookie,
402 phys_addr_t start, phys_addr_t end)
404 struct iova_domain *iovad = &cookie->iovad;
405 struct iommu_dma_msi_page *msi_page;
408 start -= iova_offset(iovad, start);
409 num_pages = iova_align(iovad, end - start) >> iova_shift(iovad);
411 for (i = 0; i < num_pages; i++) {
412 msi_page = kmalloc(sizeof(*msi_page), GFP_KERNEL);
416 msi_page->phys = start;
417 msi_page->iova = start;
418 INIT_LIST_HEAD(&msi_page->list);
419 list_add(&msi_page->list, &cookie->msi_page_list);
420 start += iovad->granule;
426 static int iommu_dma_ranges_sort(void *priv, const struct list_head *a,
427 const struct list_head *b)
429 struct resource_entry *res_a = list_entry(a, typeof(*res_a), node);
430 struct resource_entry *res_b = list_entry(b, typeof(*res_b), node);
432 return res_a->res->start > res_b->res->start;
435 static int iova_reserve_pci_windows(struct pci_dev *dev,
436 struct iova_domain *iovad)
438 struct pci_host_bridge *bridge = pci_find_host_bridge(dev->bus);
439 struct resource_entry *window;
440 unsigned long lo, hi;
441 phys_addr_t start = 0, end;
443 resource_list_for_each_entry(window, &bridge->windows) {
444 if (resource_type(window->res) != IORESOURCE_MEM)
447 lo = iova_pfn(iovad, window->res->start - window->offset);
448 hi = iova_pfn(iovad, window->res->end - window->offset);
449 reserve_iova(iovad, lo, hi);
452 /* Get reserved DMA windows from host bridge */
453 list_sort(NULL, &bridge->dma_ranges, iommu_dma_ranges_sort);
454 resource_list_for_each_entry(window, &bridge->dma_ranges) {
455 end = window->res->start - window->offset;
458 lo = iova_pfn(iovad, start);
459 hi = iova_pfn(iovad, end);
460 reserve_iova(iovad, lo, hi);
461 } else if (end < start) {
462 /* DMA ranges should be non-overlapping */
464 "Failed to reserve IOVA [%pa-%pa]\n",
469 start = window->res->end - window->offset + 1;
470 /* If window is last entry */
471 if (window->node.next == &bridge->dma_ranges &&
472 end != ~(phys_addr_t)0) {
473 end = ~(phys_addr_t)0;
481 static int iova_reserve_iommu_regions(struct device *dev,
482 struct iommu_domain *domain)
484 struct iommu_dma_cookie *cookie = domain->iova_cookie;
485 struct iova_domain *iovad = &cookie->iovad;
486 struct iommu_resv_region *region;
487 LIST_HEAD(resv_regions);
490 if (dev_is_pci(dev)) {
491 ret = iova_reserve_pci_windows(to_pci_dev(dev), iovad);
496 iommu_get_resv_regions(dev, &resv_regions);
497 list_for_each_entry(region, &resv_regions, list) {
498 unsigned long lo, hi;
500 /* We ARE the software that manages these! */
501 if (region->type == IOMMU_RESV_SW_MSI)
504 lo = iova_pfn(iovad, region->start);
505 hi = iova_pfn(iovad, region->start + region->length - 1);
506 reserve_iova(iovad, lo, hi);
508 if (region->type == IOMMU_RESV_MSI)
509 ret = cookie_init_hw_msi_region(cookie, region->start,
510 region->start + region->length);
514 iommu_put_resv_regions(dev, &resv_regions);
519 static bool dev_is_untrusted(struct device *dev)
521 return dev_is_pci(dev) && to_pci_dev(dev)->untrusted;
524 static bool dev_use_swiotlb(struct device *dev, size_t size,
525 enum dma_data_direction dir)
527 return IS_ENABLED(CONFIG_SWIOTLB) &&
528 (dev_is_untrusted(dev) ||
529 dma_kmalloc_needs_bounce(dev, size, dir));
532 static bool dev_use_sg_swiotlb(struct device *dev, struct scatterlist *sg,
533 int nents, enum dma_data_direction dir)
535 struct scatterlist *s;
538 if (!IS_ENABLED(CONFIG_SWIOTLB))
541 if (dev_is_untrusted(dev))
545 * If kmalloc() buffers are not DMA-safe for this device and
546 * direction, check the individual lengths in the sg list. If any
547 * element is deemed unsafe, use the swiotlb for bouncing.
549 if (!dma_kmalloc_safe(dev, dir)) {
550 for_each_sg(sg, s, nents, i)
551 if (!dma_kmalloc_size_aligned(s->length))
559 * iommu_dma_init_domain - Initialise a DMA mapping domain
560 * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie()
561 * @base: IOVA at which the mappable address space starts
562 * @limit: Last address of the IOVA space
563 * @dev: Device the domain is being initialised for
565 * @base and @limit + 1 should be exact multiples of IOMMU page granularity to
566 * avoid rounding surprises. If necessary, we reserve the page at address 0
567 * to ensure it is an invalid IOVA. It is safe to reinitialise a domain, but
568 * any change which could make prior IOVAs invalid will fail.
570 static int iommu_dma_init_domain(struct iommu_domain *domain, dma_addr_t base,
571 dma_addr_t limit, struct device *dev)
573 struct iommu_dma_cookie *cookie = domain->iova_cookie;
574 unsigned long order, base_pfn;
575 struct iova_domain *iovad;
578 if (!cookie || cookie->type != IOMMU_DMA_IOVA_COOKIE)
581 iovad = &cookie->iovad;
583 /* Use the smallest supported page size for IOVA granularity */
584 order = __ffs(domain->pgsize_bitmap);
585 base_pfn = max_t(unsigned long, 1, base >> order);
587 /* Check the domain allows at least some access to the device... */
588 if (domain->geometry.force_aperture) {
589 if (base > domain->geometry.aperture_end ||
590 limit < domain->geometry.aperture_start) {
591 pr_warn("specified DMA range outside IOMMU capability\n");
594 /* ...then finally give it a kicking to make sure it fits */
595 base_pfn = max_t(unsigned long, base_pfn,
596 domain->geometry.aperture_start >> order);
599 /* start_pfn is always nonzero for an already-initialised domain */
600 mutex_lock(&cookie->mutex);
601 if (iovad->start_pfn) {
602 if (1UL << order != iovad->granule ||
603 base_pfn != iovad->start_pfn) {
604 pr_warn("Incompatible range for DMA domain\n");
613 init_iova_domain(iovad, 1UL << order, base_pfn);
614 ret = iova_domain_init_rcaches(iovad);
618 /* If the FQ fails we can simply fall back to strict mode */
619 if (domain->type == IOMMU_DOMAIN_DMA_FQ &&
620 (!device_iommu_capable(dev, IOMMU_CAP_DEFERRED_FLUSH) || iommu_dma_init_fq(domain)))
621 domain->type = IOMMU_DOMAIN_DMA;
623 ret = iova_reserve_iommu_regions(dev, domain);
626 mutex_unlock(&cookie->mutex);
631 * dma_info_to_prot - Translate DMA API directions and attributes to IOMMU API
633 * @dir: Direction of DMA transfer
634 * @coherent: Is the DMA master cache-coherent?
635 * @attrs: DMA attributes for the mapping
637 * Return: corresponding IOMMU API page protection flags
639 static int dma_info_to_prot(enum dma_data_direction dir, bool coherent,
642 int prot = coherent ? IOMMU_CACHE : 0;
644 if (attrs & DMA_ATTR_PRIVILEGED)
648 case DMA_BIDIRECTIONAL:
649 return prot | IOMMU_READ | IOMMU_WRITE;
651 return prot | IOMMU_READ;
652 case DMA_FROM_DEVICE:
653 return prot | IOMMU_WRITE;
659 static dma_addr_t iommu_dma_alloc_iova(struct iommu_domain *domain,
660 size_t size, u64 dma_limit, struct device *dev)
662 struct iommu_dma_cookie *cookie = domain->iova_cookie;
663 struct iova_domain *iovad = &cookie->iovad;
664 unsigned long shift, iova_len, iova;
666 if (cookie->type == IOMMU_DMA_MSI_COOKIE) {
667 cookie->msi_iova += size;
668 return cookie->msi_iova - size;
671 shift = iova_shift(iovad);
672 iova_len = size >> shift;
674 dma_limit = min_not_zero(dma_limit, dev->bus_dma_limit);
676 if (domain->geometry.force_aperture)
677 dma_limit = min(dma_limit, (u64)domain->geometry.aperture_end);
680 * Try to use all the 32-bit PCI addresses first. The original SAC vs.
681 * DAC reasoning loses relevance with PCIe, but enough hardware and
682 * firmware bugs are still lurking out there that it's safest not to
683 * venture into the 64-bit space until necessary.
685 * If your device goes wrong after seeing the notice then likely either
686 * its driver is not setting DMA masks accurately, the hardware has
687 * some inherent bug in handling >32-bit addresses, or not all the
688 * expected address bits are wired up between the device and the IOMMU.
690 if (dma_limit > DMA_BIT_MASK(32) && dev->iommu->pci_32bit_workaround) {
691 iova = alloc_iova_fast(iovad, iova_len,
692 DMA_BIT_MASK(32) >> shift, false);
696 dev->iommu->pci_32bit_workaround = false;
697 dev_notice(dev, "Using %d-bit DMA addresses\n", bits_per(dma_limit));
700 iova = alloc_iova_fast(iovad, iova_len, dma_limit >> shift, true);
702 return (dma_addr_t)iova << shift;
705 static void iommu_dma_free_iova(struct iommu_dma_cookie *cookie,
706 dma_addr_t iova, size_t size, struct iommu_iotlb_gather *gather)
708 struct iova_domain *iovad = &cookie->iovad;
710 /* The MSI case is only ever cleaning up its most recent allocation */
711 if (cookie->type == IOMMU_DMA_MSI_COOKIE)
712 cookie->msi_iova -= size;
713 else if (gather && gather->queued)
714 queue_iova(cookie, iova_pfn(iovad, iova),
715 size >> iova_shift(iovad),
718 free_iova_fast(iovad, iova_pfn(iovad, iova),
719 size >> iova_shift(iovad));
722 static void __iommu_dma_unmap(struct device *dev, dma_addr_t dma_addr,
725 struct iommu_domain *domain = iommu_get_dma_domain(dev);
726 struct iommu_dma_cookie *cookie = domain->iova_cookie;
727 struct iova_domain *iovad = &cookie->iovad;
728 size_t iova_off = iova_offset(iovad, dma_addr);
729 struct iommu_iotlb_gather iotlb_gather;
732 dma_addr -= iova_off;
733 size = iova_align(iovad, size + iova_off);
734 iommu_iotlb_gather_init(&iotlb_gather);
735 iotlb_gather.queued = READ_ONCE(cookie->fq_domain);
737 unmapped = iommu_unmap_fast(domain, dma_addr, size, &iotlb_gather);
738 WARN_ON(unmapped != size);
740 if (!iotlb_gather.queued)
741 iommu_iotlb_sync(domain, &iotlb_gather);
742 iommu_dma_free_iova(cookie, dma_addr, size, &iotlb_gather);
745 static dma_addr_t __iommu_dma_map(struct device *dev, phys_addr_t phys,
746 size_t size, int prot, u64 dma_mask)
748 struct iommu_domain *domain = iommu_get_dma_domain(dev);
749 struct iommu_dma_cookie *cookie = domain->iova_cookie;
750 struct iova_domain *iovad = &cookie->iovad;
751 size_t iova_off = iova_offset(iovad, phys);
754 if (static_branch_unlikely(&iommu_deferred_attach_enabled) &&
755 iommu_deferred_attach(dev, domain))
756 return DMA_MAPPING_ERROR;
758 size = iova_align(iovad, size + iova_off);
760 iova = iommu_dma_alloc_iova(domain, size, dma_mask, dev);
762 return DMA_MAPPING_ERROR;
764 if (iommu_map(domain, iova, phys - iova_off, size, prot, GFP_ATOMIC)) {
765 iommu_dma_free_iova(cookie, iova, size, NULL);
766 return DMA_MAPPING_ERROR;
768 return iova + iova_off;
771 static void __iommu_dma_free_pages(struct page **pages, int count)
774 __free_page(pages[count]);
778 static struct page **__iommu_dma_alloc_pages(struct device *dev,
779 unsigned int count, unsigned long order_mask, gfp_t gfp)
782 unsigned int i = 0, nid = dev_to_node(dev);
784 order_mask &= GENMASK(MAX_ORDER, 0);
788 pages = kvcalloc(count, sizeof(*pages), GFP_KERNEL);
792 /* IOMMU can map any pages, so himem can also be used here */
793 gfp |= __GFP_NOWARN | __GFP_HIGHMEM;
796 struct page *page = NULL;
797 unsigned int order_size;
800 * Higher-order allocations are a convenience rather
801 * than a necessity, hence using __GFP_NORETRY until
802 * falling back to minimum-order allocations.
804 for (order_mask &= GENMASK(__fls(count), 0);
805 order_mask; order_mask &= ~order_size) {
806 unsigned int order = __fls(order_mask);
807 gfp_t alloc_flags = gfp;
809 order_size = 1U << order;
810 if (order_mask > order_size)
811 alloc_flags |= __GFP_NORETRY;
812 page = alloc_pages_node(nid, alloc_flags, order);
816 split_page(page, order);
820 __iommu_dma_free_pages(pages, i);
831 * If size is less than PAGE_SIZE, then a full CPU page will be allocated,
832 * but an IOMMU which supports smaller pages might not map the whole thing.
834 static struct page **__iommu_dma_alloc_noncontiguous(struct device *dev,
835 size_t size, struct sg_table *sgt, gfp_t gfp, pgprot_t prot,
838 struct iommu_domain *domain = iommu_get_dma_domain(dev);
839 struct iommu_dma_cookie *cookie = domain->iova_cookie;
840 struct iova_domain *iovad = &cookie->iovad;
841 bool coherent = dev_is_dma_coherent(dev);
842 int ioprot = dma_info_to_prot(DMA_BIDIRECTIONAL, coherent, attrs);
843 unsigned int count, min_size, alloc_sizes = domain->pgsize_bitmap;
848 if (static_branch_unlikely(&iommu_deferred_attach_enabled) &&
849 iommu_deferred_attach(dev, domain))
852 min_size = alloc_sizes & -alloc_sizes;
853 if (min_size < PAGE_SIZE) {
854 min_size = PAGE_SIZE;
855 alloc_sizes |= PAGE_SIZE;
857 size = ALIGN(size, min_size);
859 if (attrs & DMA_ATTR_ALLOC_SINGLE_PAGES)
860 alloc_sizes = min_size;
862 count = PAGE_ALIGN(size) >> PAGE_SHIFT;
863 pages = __iommu_dma_alloc_pages(dev, count, alloc_sizes >> PAGE_SHIFT,
868 size = iova_align(iovad, size);
869 iova = iommu_dma_alloc_iova(domain, size, dev->coherent_dma_mask, dev);
874 * Remove the zone/policy flags from the GFP - these are applied to the
875 * __iommu_dma_alloc_pages() but are not used for the supporting
876 * internal allocations that follow.
878 gfp &= ~(__GFP_DMA | __GFP_DMA32 | __GFP_HIGHMEM | __GFP_COMP);
880 if (sg_alloc_table_from_pages(sgt, pages, count, 0, size, gfp))
883 if (!(ioprot & IOMMU_CACHE)) {
884 struct scatterlist *sg;
887 for_each_sg(sgt->sgl, sg, sgt->orig_nents, i)
888 arch_dma_prep_coherent(sg_page(sg), sg->length);
891 ret = iommu_map_sg(domain, iova, sgt->sgl, sgt->orig_nents, ioprot,
893 if (ret < 0 || ret < size)
896 sgt->sgl->dma_address = iova;
897 sgt->sgl->dma_length = size;
903 iommu_dma_free_iova(cookie, iova, size, NULL);
905 __iommu_dma_free_pages(pages, count);
909 static void *iommu_dma_alloc_remap(struct device *dev, size_t size,
910 dma_addr_t *dma_handle, gfp_t gfp, pgprot_t prot,
917 pages = __iommu_dma_alloc_noncontiguous(dev, size, &sgt, gfp, prot,
921 *dma_handle = sgt.sgl->dma_address;
923 vaddr = dma_common_pages_remap(pages, size, prot,
924 __builtin_return_address(0));
930 __iommu_dma_unmap(dev, *dma_handle, size);
931 __iommu_dma_free_pages(pages, PAGE_ALIGN(size) >> PAGE_SHIFT);
935 static struct sg_table *iommu_dma_alloc_noncontiguous(struct device *dev,
936 size_t size, enum dma_data_direction dir, gfp_t gfp,
939 struct dma_sgt_handle *sh;
941 sh = kmalloc(sizeof(*sh), gfp);
945 sh->pages = __iommu_dma_alloc_noncontiguous(dev, size, &sh->sgt, gfp,
954 static void iommu_dma_free_noncontiguous(struct device *dev, size_t size,
955 struct sg_table *sgt, enum dma_data_direction dir)
957 struct dma_sgt_handle *sh = sgt_handle(sgt);
959 __iommu_dma_unmap(dev, sgt->sgl->dma_address, size);
960 __iommu_dma_free_pages(sh->pages, PAGE_ALIGN(size) >> PAGE_SHIFT);
961 sg_free_table(&sh->sgt);
965 static void iommu_dma_sync_single_for_cpu(struct device *dev,
966 dma_addr_t dma_handle, size_t size, enum dma_data_direction dir)
970 if (dev_is_dma_coherent(dev) && !dev_use_swiotlb(dev, size, dir))
973 phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle);
974 if (!dev_is_dma_coherent(dev))
975 arch_sync_dma_for_cpu(phys, size, dir);
977 if (is_swiotlb_buffer(dev, phys))
978 swiotlb_sync_single_for_cpu(dev, phys, size, dir);
981 static void iommu_dma_sync_single_for_device(struct device *dev,
982 dma_addr_t dma_handle, size_t size, enum dma_data_direction dir)
986 if (dev_is_dma_coherent(dev) && !dev_use_swiotlb(dev, size, dir))
989 phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle);
990 if (is_swiotlb_buffer(dev, phys))
991 swiotlb_sync_single_for_device(dev, phys, size, dir);
993 if (!dev_is_dma_coherent(dev))
994 arch_sync_dma_for_device(phys, size, dir);
997 static void iommu_dma_sync_sg_for_cpu(struct device *dev,
998 struct scatterlist *sgl, int nelems,
999 enum dma_data_direction dir)
1001 struct scatterlist *sg;
1004 if (sg_dma_is_swiotlb(sgl))
1005 for_each_sg(sgl, sg, nelems, i)
1006 iommu_dma_sync_single_for_cpu(dev, sg_dma_address(sg),
1008 else if (!dev_is_dma_coherent(dev))
1009 for_each_sg(sgl, sg, nelems, i)
1010 arch_sync_dma_for_cpu(sg_phys(sg), sg->length, dir);
1013 static void iommu_dma_sync_sg_for_device(struct device *dev,
1014 struct scatterlist *sgl, int nelems,
1015 enum dma_data_direction dir)
1017 struct scatterlist *sg;
1020 if (sg_dma_is_swiotlb(sgl))
1021 for_each_sg(sgl, sg, nelems, i)
1022 iommu_dma_sync_single_for_device(dev,
1025 else if (!dev_is_dma_coherent(dev))
1026 for_each_sg(sgl, sg, nelems, i)
1027 arch_sync_dma_for_device(sg_phys(sg), sg->length, dir);
1030 static dma_addr_t iommu_dma_map_page(struct device *dev, struct page *page,
1031 unsigned long offset, size_t size, enum dma_data_direction dir,
1032 unsigned long attrs)
1034 phys_addr_t phys = page_to_phys(page) + offset;
1035 bool coherent = dev_is_dma_coherent(dev);
1036 int prot = dma_info_to_prot(dir, coherent, attrs);
1037 struct iommu_domain *domain = iommu_get_dma_domain(dev);
1038 struct iommu_dma_cookie *cookie = domain->iova_cookie;
1039 struct iova_domain *iovad = &cookie->iovad;
1040 dma_addr_t iova, dma_mask = dma_get_mask(dev);
1043 * If both the physical buffer start address and size are
1044 * page aligned, we don't need to use a bounce page.
1046 if (dev_use_swiotlb(dev, size, dir) &&
1047 iova_offset(iovad, phys | size)) {
1048 void *padding_start;
1049 size_t padding_size, aligned_size;
1051 if (!is_swiotlb_active(dev)) {
1052 dev_warn_once(dev, "DMA bounce buffers are inactive, unable to map unaligned transaction.\n");
1053 return DMA_MAPPING_ERROR;
1056 trace_swiotlb_bounced(dev, phys, size);
1058 aligned_size = iova_align(iovad, size);
1059 phys = swiotlb_tbl_map_single(dev, phys, size, aligned_size,
1060 iova_mask(iovad), dir, attrs);
1062 if (phys == DMA_MAPPING_ERROR)
1063 return DMA_MAPPING_ERROR;
1065 /* Cleanup the padding area. */
1066 padding_start = phys_to_virt(phys);
1067 padding_size = aligned_size;
1069 if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
1070 (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL)) {
1071 padding_start += size;
1072 padding_size -= size;
1075 memset(padding_start, 0, padding_size);
1078 if (!coherent && !(attrs & DMA_ATTR_SKIP_CPU_SYNC))
1079 arch_sync_dma_for_device(phys, size, dir);
1081 iova = __iommu_dma_map(dev, phys, size, prot, dma_mask);
1082 if (iova == DMA_MAPPING_ERROR && is_swiotlb_buffer(dev, phys))
1083 swiotlb_tbl_unmap_single(dev, phys, size, dir, attrs);
1087 static void iommu_dma_unmap_page(struct device *dev, dma_addr_t dma_handle,
1088 size_t size, enum dma_data_direction dir, unsigned long attrs)
1090 struct iommu_domain *domain = iommu_get_dma_domain(dev);
1093 phys = iommu_iova_to_phys(domain, dma_handle);
1097 if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) && !dev_is_dma_coherent(dev))
1098 arch_sync_dma_for_cpu(phys, size, dir);
1100 __iommu_dma_unmap(dev, dma_handle, size);
1102 if (unlikely(is_swiotlb_buffer(dev, phys)))
1103 swiotlb_tbl_unmap_single(dev, phys, size, dir, attrs);
1107 * Prepare a successfully-mapped scatterlist to give back to the caller.
1109 * At this point the segments are already laid out by iommu_dma_map_sg() to
1110 * avoid individually crossing any boundaries, so we merely need to check a
1111 * segment's start address to avoid concatenating across one.
1113 static int __finalise_sg(struct device *dev, struct scatterlist *sg, int nents,
1114 dma_addr_t dma_addr)
1116 struct scatterlist *s, *cur = sg;
1117 unsigned long seg_mask = dma_get_seg_boundary(dev);
1118 unsigned int cur_len = 0, max_len = dma_get_max_seg_size(dev);
1121 for_each_sg(sg, s, nents, i) {
1122 /* Restore this segment's original unaligned fields first */
1123 dma_addr_t s_dma_addr = sg_dma_address(s);
1124 unsigned int s_iova_off = sg_dma_address(s);
1125 unsigned int s_length = sg_dma_len(s);
1126 unsigned int s_iova_len = s->length;
1128 sg_dma_address(s) = DMA_MAPPING_ERROR;
1131 if (sg_dma_is_bus_address(s)) {
1135 sg_dma_unmark_bus_address(s);
1136 sg_dma_address(cur) = s_dma_addr;
1137 sg_dma_len(cur) = s_length;
1138 sg_dma_mark_bus_address(cur);
1144 s->offset += s_iova_off;
1145 s->length = s_length;
1148 * Now fill in the real DMA data. If...
1149 * - there is a valid output segment to append to
1150 * - and this segment starts on an IOVA page boundary
1151 * - but doesn't fall at a segment boundary
1152 * - and wouldn't make the resulting output segment too long
1154 if (cur_len && !s_iova_off && (dma_addr & seg_mask) &&
1155 (max_len - cur_len >= s_length)) {
1156 /* ...then concatenate it with the previous one */
1157 cur_len += s_length;
1159 /* Otherwise start the next output segment */
1165 sg_dma_address(cur) = dma_addr + s_iova_off;
1168 sg_dma_len(cur) = cur_len;
1169 dma_addr += s_iova_len;
1171 if (s_length + s_iova_off < s_iova_len)
1178 * If mapping failed, then just restore the original list,
1179 * but making sure the DMA fields are invalidated.
1181 static void __invalidate_sg(struct scatterlist *sg, int nents)
1183 struct scatterlist *s;
1186 for_each_sg(sg, s, nents, i) {
1187 if (sg_dma_is_bus_address(s)) {
1188 sg_dma_unmark_bus_address(s);
1190 if (sg_dma_address(s) != DMA_MAPPING_ERROR)
1191 s->offset += sg_dma_address(s);
1193 s->length = sg_dma_len(s);
1195 sg_dma_address(s) = DMA_MAPPING_ERROR;
1200 static void iommu_dma_unmap_sg_swiotlb(struct device *dev, struct scatterlist *sg,
1201 int nents, enum dma_data_direction dir, unsigned long attrs)
1203 struct scatterlist *s;
1206 for_each_sg(sg, s, nents, i)
1207 iommu_dma_unmap_page(dev, sg_dma_address(s),
1208 sg_dma_len(s), dir, attrs);
1211 static int iommu_dma_map_sg_swiotlb(struct device *dev, struct scatterlist *sg,
1212 int nents, enum dma_data_direction dir, unsigned long attrs)
1214 struct scatterlist *s;
1217 sg_dma_mark_swiotlb(sg);
1219 for_each_sg(sg, s, nents, i) {
1220 sg_dma_address(s) = iommu_dma_map_page(dev, sg_page(s),
1221 s->offset, s->length, dir, attrs);
1222 if (sg_dma_address(s) == DMA_MAPPING_ERROR)
1224 sg_dma_len(s) = s->length;
1230 iommu_dma_unmap_sg_swiotlb(dev, sg, i, dir, attrs | DMA_ATTR_SKIP_CPU_SYNC);
1235 * The DMA API client is passing in a scatterlist which could describe
1236 * any old buffer layout, but the IOMMU API requires everything to be
1237 * aligned to IOMMU pages. Hence the need for this complicated bit of
1238 * impedance-matching, to be able to hand off a suitably-aligned list,
1239 * but still preserve the original offsets and sizes for the caller.
1241 static int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg,
1242 int nents, enum dma_data_direction dir, unsigned long attrs)
1244 struct iommu_domain *domain = iommu_get_dma_domain(dev);
1245 struct iommu_dma_cookie *cookie = domain->iova_cookie;
1246 struct iova_domain *iovad = &cookie->iovad;
1247 struct scatterlist *s, *prev = NULL;
1248 int prot = dma_info_to_prot(dir, dev_is_dma_coherent(dev), attrs);
1249 struct pci_p2pdma_map_state p2pdma_state = {};
1250 enum pci_p2pdma_map_type map;
1252 size_t iova_len = 0;
1253 unsigned long mask = dma_get_seg_boundary(dev);
1257 if (static_branch_unlikely(&iommu_deferred_attach_enabled)) {
1258 ret = iommu_deferred_attach(dev, domain);
1263 if (dev_use_sg_swiotlb(dev, sg, nents, dir))
1264 return iommu_dma_map_sg_swiotlb(dev, sg, nents, dir, attrs);
1266 if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
1267 iommu_dma_sync_sg_for_device(dev, sg, nents, dir);
1270 * Work out how much IOVA space we need, and align the segments to
1271 * IOVA granules for the IOMMU driver to handle. With some clever
1272 * trickery we can modify the list in-place, but reversibly, by
1273 * stashing the unaligned parts in the as-yet-unused DMA fields.
1275 for_each_sg(sg, s, nents, i) {
1276 size_t s_iova_off = iova_offset(iovad, s->offset);
1277 size_t s_length = s->length;
1278 size_t pad_len = (mask - iova_len + 1) & mask;
1280 if (is_pci_p2pdma_page(sg_page(s))) {
1281 map = pci_p2pdma_map_segment(&p2pdma_state, dev, s);
1283 case PCI_P2PDMA_MAP_BUS_ADDR:
1285 * iommu_map_sg() will skip this segment as
1286 * it is marked as a bus address,
1287 * __finalise_sg() will copy the dma address
1288 * into the output segment.
1291 case PCI_P2PDMA_MAP_THRU_HOST_BRIDGE:
1293 * Mapping through host bridge should be
1294 * mapped with regular IOVAs, thus we
1295 * do nothing here and continue below.
1300 goto out_restore_sg;
1304 sg_dma_address(s) = s_iova_off;
1305 sg_dma_len(s) = s_length;
1306 s->offset -= s_iova_off;
1307 s_length = iova_align(iovad, s_length + s_iova_off);
1308 s->length = s_length;
1311 * Due to the alignment of our single IOVA allocation, we can
1312 * depend on these assumptions about the segment boundary mask:
1313 * - If mask size >= IOVA size, then the IOVA range cannot
1314 * possibly fall across a boundary, so we don't care.
1315 * - If mask size < IOVA size, then the IOVA range must start
1316 * exactly on a boundary, therefore we can lay things out
1317 * based purely on segment lengths without needing to know
1318 * the actual addresses beforehand.
1319 * - The mask must be a power of 2, so pad_len == 0 if
1320 * iova_len == 0, thus we cannot dereference prev the first
1321 * time through here (i.e. before it has a meaningful value).
1323 if (pad_len && pad_len < s_length - 1) {
1324 prev->length += pad_len;
1325 iova_len += pad_len;
1328 iova_len += s_length;
1333 return __finalise_sg(dev, sg, nents, 0);
1335 iova = iommu_dma_alloc_iova(domain, iova_len, dma_get_mask(dev), dev);
1338 goto out_restore_sg;
1342 * We'll leave any physical concatenation to the IOMMU driver's
1343 * implementation - it knows better than we do.
1345 ret = iommu_map_sg(domain, iova, sg, nents, prot, GFP_ATOMIC);
1346 if (ret < 0 || ret < iova_len)
1349 return __finalise_sg(dev, sg, nents, iova);
1352 iommu_dma_free_iova(cookie, iova, iova_len, NULL);
1354 __invalidate_sg(sg, nents);
1356 if (ret != -ENOMEM && ret != -EREMOTEIO)
1361 static void iommu_dma_unmap_sg(struct device *dev, struct scatterlist *sg,
1362 int nents, enum dma_data_direction dir, unsigned long attrs)
1364 dma_addr_t end = 0, start;
1365 struct scatterlist *tmp;
1368 if (sg_dma_is_swiotlb(sg)) {
1369 iommu_dma_unmap_sg_swiotlb(dev, sg, nents, dir, attrs);
1373 if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
1374 iommu_dma_sync_sg_for_cpu(dev, sg, nents, dir);
1377 * The scatterlist segments are mapped into a single
1378 * contiguous IOVA allocation, the start and end points
1379 * just have to be determined.
1381 for_each_sg(sg, tmp, nents, i) {
1382 if (sg_dma_is_bus_address(tmp)) {
1383 sg_dma_unmark_bus_address(tmp);
1387 if (sg_dma_len(tmp) == 0)
1390 start = sg_dma_address(tmp);
1395 for_each_sg(tmp, tmp, nents, i) {
1396 if (sg_dma_is_bus_address(tmp)) {
1397 sg_dma_unmark_bus_address(tmp);
1401 if (sg_dma_len(tmp) == 0)
1404 end = sg_dma_address(tmp) + sg_dma_len(tmp);
1408 __iommu_dma_unmap(dev, start, end - start);
1411 static dma_addr_t iommu_dma_map_resource(struct device *dev, phys_addr_t phys,
1412 size_t size, enum dma_data_direction dir, unsigned long attrs)
1414 return __iommu_dma_map(dev, phys, size,
1415 dma_info_to_prot(dir, false, attrs) | IOMMU_MMIO,
1419 static void iommu_dma_unmap_resource(struct device *dev, dma_addr_t handle,
1420 size_t size, enum dma_data_direction dir, unsigned long attrs)
1422 __iommu_dma_unmap(dev, handle, size);
1425 static void __iommu_dma_free(struct device *dev, size_t size, void *cpu_addr)
1427 size_t alloc_size = PAGE_ALIGN(size);
1428 int count = alloc_size >> PAGE_SHIFT;
1429 struct page *page = NULL, **pages = NULL;
1431 /* Non-coherent atomic allocation? Easy */
1432 if (IS_ENABLED(CONFIG_DMA_DIRECT_REMAP) &&
1433 dma_free_from_pool(dev, cpu_addr, alloc_size))
1436 if (is_vmalloc_addr(cpu_addr)) {
1438 * If it the address is remapped, then it's either non-coherent
1439 * or highmem CMA, or an iommu_dma_alloc_remap() construction.
1441 pages = dma_common_find_pages(cpu_addr);
1443 page = vmalloc_to_page(cpu_addr);
1444 dma_common_free_remap(cpu_addr, alloc_size);
1446 /* Lowmem means a coherent atomic or CMA allocation */
1447 page = virt_to_page(cpu_addr);
1451 __iommu_dma_free_pages(pages, count);
1453 dma_free_contiguous(dev, page, alloc_size);
1456 static void iommu_dma_free(struct device *dev, size_t size, void *cpu_addr,
1457 dma_addr_t handle, unsigned long attrs)
1459 __iommu_dma_unmap(dev, handle, size);
1460 __iommu_dma_free(dev, size, cpu_addr);
1463 static void *iommu_dma_alloc_pages(struct device *dev, size_t size,
1464 struct page **pagep, gfp_t gfp, unsigned long attrs)
1466 bool coherent = dev_is_dma_coherent(dev);
1467 size_t alloc_size = PAGE_ALIGN(size);
1468 int node = dev_to_node(dev);
1469 struct page *page = NULL;
1472 page = dma_alloc_contiguous(dev, alloc_size, gfp);
1474 page = alloc_pages_node(node, gfp, get_order(alloc_size));
1478 if (!coherent || PageHighMem(page)) {
1479 pgprot_t prot = dma_pgprot(dev, PAGE_KERNEL, attrs);
1481 cpu_addr = dma_common_contiguous_remap(page, alloc_size,
1482 prot, __builtin_return_address(0));
1484 goto out_free_pages;
1487 arch_dma_prep_coherent(page, size);
1489 cpu_addr = page_address(page);
1493 memset(cpu_addr, 0, alloc_size);
1496 dma_free_contiguous(dev, page, alloc_size);
1500 static void *iommu_dma_alloc(struct device *dev, size_t size,
1501 dma_addr_t *handle, gfp_t gfp, unsigned long attrs)
1503 bool coherent = dev_is_dma_coherent(dev);
1504 int ioprot = dma_info_to_prot(DMA_BIDIRECTIONAL, coherent, attrs);
1505 struct page *page = NULL;
1510 if (gfpflags_allow_blocking(gfp) &&
1511 !(attrs & DMA_ATTR_FORCE_CONTIGUOUS)) {
1512 return iommu_dma_alloc_remap(dev, size, handle, gfp,
1513 dma_pgprot(dev, PAGE_KERNEL, attrs), attrs);
1516 if (IS_ENABLED(CONFIG_DMA_DIRECT_REMAP) &&
1517 !gfpflags_allow_blocking(gfp) && !coherent)
1518 page = dma_alloc_from_pool(dev, PAGE_ALIGN(size), &cpu_addr,
1521 cpu_addr = iommu_dma_alloc_pages(dev, size, &page, gfp, attrs);
1525 *handle = __iommu_dma_map(dev, page_to_phys(page), size, ioprot,
1526 dev->coherent_dma_mask);
1527 if (*handle == DMA_MAPPING_ERROR) {
1528 __iommu_dma_free(dev, size, cpu_addr);
1535 static int iommu_dma_mmap(struct device *dev, struct vm_area_struct *vma,
1536 void *cpu_addr, dma_addr_t dma_addr, size_t size,
1537 unsigned long attrs)
1539 unsigned long nr_pages = PAGE_ALIGN(size) >> PAGE_SHIFT;
1540 unsigned long pfn, off = vma->vm_pgoff;
1543 vma->vm_page_prot = dma_pgprot(dev, vma->vm_page_prot, attrs);
1545 if (dma_mmap_from_dev_coherent(dev, vma, cpu_addr, size, &ret))
1548 if (off >= nr_pages || vma_pages(vma) > nr_pages - off)
1551 if (is_vmalloc_addr(cpu_addr)) {
1552 struct page **pages = dma_common_find_pages(cpu_addr);
1555 return vm_map_pages(vma, pages, nr_pages);
1556 pfn = vmalloc_to_pfn(cpu_addr);
1558 pfn = page_to_pfn(virt_to_page(cpu_addr));
1561 return remap_pfn_range(vma, vma->vm_start, pfn + off,
1562 vma->vm_end - vma->vm_start,
1566 static int iommu_dma_get_sgtable(struct device *dev, struct sg_table *sgt,
1567 void *cpu_addr, dma_addr_t dma_addr, size_t size,
1568 unsigned long attrs)
1573 if (is_vmalloc_addr(cpu_addr)) {
1574 struct page **pages = dma_common_find_pages(cpu_addr);
1577 return sg_alloc_table_from_pages(sgt, pages,
1578 PAGE_ALIGN(size) >> PAGE_SHIFT,
1579 0, size, GFP_KERNEL);
1582 page = vmalloc_to_page(cpu_addr);
1584 page = virt_to_page(cpu_addr);
1587 ret = sg_alloc_table(sgt, 1, GFP_KERNEL);
1589 sg_set_page(sgt->sgl, page, PAGE_ALIGN(size), 0);
1593 static unsigned long iommu_dma_get_merge_boundary(struct device *dev)
1595 struct iommu_domain *domain = iommu_get_dma_domain(dev);
1597 return (1UL << __ffs(domain->pgsize_bitmap)) - 1;
1600 static size_t iommu_dma_opt_mapping_size(void)
1602 return iova_rcache_range();
1605 static const struct dma_map_ops iommu_dma_ops = {
1606 .flags = DMA_F_PCI_P2PDMA_SUPPORTED,
1607 .alloc = iommu_dma_alloc,
1608 .free = iommu_dma_free,
1609 .alloc_pages = dma_common_alloc_pages,
1610 .free_pages = dma_common_free_pages,
1611 .alloc_noncontiguous = iommu_dma_alloc_noncontiguous,
1612 .free_noncontiguous = iommu_dma_free_noncontiguous,
1613 .mmap = iommu_dma_mmap,
1614 .get_sgtable = iommu_dma_get_sgtable,
1615 .map_page = iommu_dma_map_page,
1616 .unmap_page = iommu_dma_unmap_page,
1617 .map_sg = iommu_dma_map_sg,
1618 .unmap_sg = iommu_dma_unmap_sg,
1619 .sync_single_for_cpu = iommu_dma_sync_single_for_cpu,
1620 .sync_single_for_device = iommu_dma_sync_single_for_device,
1621 .sync_sg_for_cpu = iommu_dma_sync_sg_for_cpu,
1622 .sync_sg_for_device = iommu_dma_sync_sg_for_device,
1623 .map_resource = iommu_dma_map_resource,
1624 .unmap_resource = iommu_dma_unmap_resource,
1625 .get_merge_boundary = iommu_dma_get_merge_boundary,
1626 .opt_mapping_size = iommu_dma_opt_mapping_size,
1630 * The IOMMU core code allocates the default DMA domain, which the underlying
1631 * IOMMU driver needs to support via the dma-iommu layer.
1633 void iommu_setup_dma_ops(struct device *dev, u64 dma_base, u64 dma_limit)
1635 struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
1641 * The IOMMU core code allocates the default DMA domain, which the
1642 * underlying IOMMU driver needs to support via the dma-iommu layer.
1644 if (iommu_is_dma_domain(domain)) {
1645 if (iommu_dma_init_domain(domain, dma_base, dma_limit, dev))
1647 dev->dma_ops = &iommu_dma_ops;
1652 pr_warn("Failed to set up IOMMU for device %s; retaining platform DMA ops\n",
1655 EXPORT_SYMBOL_GPL(iommu_setup_dma_ops);
1657 static struct iommu_dma_msi_page *iommu_dma_get_msi_page(struct device *dev,
1658 phys_addr_t msi_addr, struct iommu_domain *domain)
1660 struct iommu_dma_cookie *cookie = domain->iova_cookie;
1661 struct iommu_dma_msi_page *msi_page;
1663 int prot = IOMMU_WRITE | IOMMU_NOEXEC | IOMMU_MMIO;
1664 size_t size = cookie_msi_granule(cookie);
1666 msi_addr &= ~(phys_addr_t)(size - 1);
1667 list_for_each_entry(msi_page, &cookie->msi_page_list, list)
1668 if (msi_page->phys == msi_addr)
1671 msi_page = kzalloc(sizeof(*msi_page), GFP_KERNEL);
1675 iova = iommu_dma_alloc_iova(domain, size, dma_get_mask(dev), dev);
1679 if (iommu_map(domain, iova, msi_addr, size, prot, GFP_KERNEL))
1682 INIT_LIST_HEAD(&msi_page->list);
1683 msi_page->phys = msi_addr;
1684 msi_page->iova = iova;
1685 list_add(&msi_page->list, &cookie->msi_page_list);
1689 iommu_dma_free_iova(cookie, iova, size, NULL);
1696 * iommu_dma_prepare_msi() - Map the MSI page in the IOMMU domain
1697 * @desc: MSI descriptor, will store the MSI page
1698 * @msi_addr: MSI target address to be mapped
1700 * Return: 0 on success or negative error code if the mapping failed.
1702 int iommu_dma_prepare_msi(struct msi_desc *desc, phys_addr_t msi_addr)
1704 struct device *dev = msi_desc_to_dev(desc);
1705 struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
1706 struct iommu_dma_msi_page *msi_page;
1707 static DEFINE_MUTEX(msi_prepare_lock); /* see below */
1709 if (!domain || !domain->iova_cookie) {
1710 desc->iommu_cookie = NULL;
1715 * In fact the whole prepare operation should already be serialised by
1716 * irq_domain_mutex further up the callchain, but that's pretty subtle
1717 * on its own, so consider this locking as failsafe documentation...
1719 mutex_lock(&msi_prepare_lock);
1720 msi_page = iommu_dma_get_msi_page(dev, msi_addr, domain);
1721 mutex_unlock(&msi_prepare_lock);
1723 msi_desc_set_iommu_cookie(desc, msi_page);
1731 * iommu_dma_compose_msi_msg() - Apply translation to an MSI message
1732 * @desc: MSI descriptor prepared by iommu_dma_prepare_msi()
1733 * @msg: MSI message containing target physical address
1735 void iommu_dma_compose_msi_msg(struct msi_desc *desc, struct msi_msg *msg)
1737 struct device *dev = msi_desc_to_dev(desc);
1738 const struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
1739 const struct iommu_dma_msi_page *msi_page;
1741 msi_page = msi_desc_get_iommu_cookie(desc);
1743 if (!domain || !domain->iova_cookie || WARN_ON(!msi_page))
1746 msg->address_hi = upper_32_bits(msi_page->iova);
1747 msg->address_lo &= cookie_msi_granule(domain->iova_cookie) - 1;
1748 msg->address_lo += lower_32_bits(msi_page->iova);
1751 static int iommu_dma_init(void)
1753 if (is_kdump_kernel())
1754 static_branch_enable(&iommu_deferred_attach_enabled);
1756 return iova_cache_get();
1758 arch_initcall(iommu_dma_init);