Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * A fairly generic DMA-API to IOMMU-API glue layer.
4 *
5 * Copyright (C) 2014-2015 ARM Ltd.
6 *
7 * based in part on arch/arm/mm/dma-mapping.c:
8 * Copyright (C) 2000-2004 Russell King
9 */
10
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/iommu-dma.h>
21#include <linux/iova.h>
22#include <linux/irq.h>
23#include <linux/list_sort.h>
24#include <linux/memremap.h>
25#include <linux/mm.h>
26#include <linux/mutex.h>
27#include <linux/msi.h>
28#include <linux/of_iommu.h>
29#include <linux/pci.h>
30#include <linux/scatterlist.h>
31#include <linux/spinlock.h>
32#include <linux/swiotlb.h>
33#include <linux/vmalloc.h>
34#include <trace/events/swiotlb.h>
35
36#include "dma-iommu.h"
37#include "iommu-pages.h"
38
39struct iommu_dma_msi_page {
40 struct list_head list;
41 dma_addr_t iova;
42 phys_addr_t phys;
43};
44
45enum iommu_dma_queue_type {
46 IOMMU_DMA_OPTS_PER_CPU_QUEUE,
47 IOMMU_DMA_OPTS_SINGLE_QUEUE,
48};
49
50struct iommu_dma_options {
51 enum iommu_dma_queue_type qt;
52 size_t fq_size;
53 unsigned int fq_timeout;
54};
55
56struct iommu_dma_cookie {
57 struct iova_domain iovad;
58 struct list_head msi_page_list;
59 /* Flush queue */
60 union {
61 struct iova_fq *single_fq;
62 struct iova_fq __percpu *percpu_fq;
63 };
64 /* Number of TLB flushes that have been started */
65 atomic64_t fq_flush_start_cnt;
66 /* Number of TLB flushes that have been finished */
67 atomic64_t fq_flush_finish_cnt;
68 /* Timer to regularily empty the flush queues */
69 struct timer_list fq_timer;
70 /* 1 when timer is active, 0 when not */
71 atomic_t fq_timer_on;
72 /* Domain for flush queue callback; NULL if flush queue not in use */
73 struct iommu_domain *fq_domain;
74 /* Options for dma-iommu use */
75 struct iommu_dma_options options;
76};
77
78struct iommu_dma_msi_cookie {
79 dma_addr_t msi_iova;
80 struct list_head msi_page_list;
81};
82
83static DEFINE_STATIC_KEY_FALSE(iommu_deferred_attach_enabled);
84bool iommu_dma_forcedac __read_mostly;
85
86static int __init iommu_dma_forcedac_setup(char *str)
87{
88 int ret = kstrtobool(str, &iommu_dma_forcedac);
89
90 if (!ret && iommu_dma_forcedac)
91 pr_info("Forcing DAC for PCI devices\n");
92 return ret;
93}
94early_param("iommu.forcedac", iommu_dma_forcedac_setup);
95
96/* Number of entries per flush queue */
97#define IOVA_DEFAULT_FQ_SIZE 256
98#define IOVA_SINGLE_FQ_SIZE 32768
99
100/* Timeout (in ms) after which entries are flushed from the queue */
101#define IOVA_DEFAULT_FQ_TIMEOUT 10
102#define IOVA_SINGLE_FQ_TIMEOUT 1000
103
104/* Flush queue entry for deferred flushing */
105struct iova_fq_entry {
106 unsigned long iova_pfn;
107 unsigned long pages;
108 struct list_head freelist;
109 u64 counter; /* Flush counter when this entry was added */
110};
111
112/* Per-CPU flush queue structure */
113struct iova_fq {
114 spinlock_t lock;
115 unsigned int head, tail;
116 unsigned int mod_mask;
117 struct iova_fq_entry entries[];
118};
119
120#define fq_ring_for_each(i, fq) \
121 for ((i) = (fq)->head; (i) != (fq)->tail; (i) = ((i) + 1) & (fq)->mod_mask)
122
123static inline bool fq_full(struct iova_fq *fq)
124{
125 assert_spin_locked(&fq->lock);
126 return (((fq->tail + 1) & fq->mod_mask) == fq->head);
127}
128
129static inline unsigned int fq_ring_add(struct iova_fq *fq)
130{
131 unsigned int idx = fq->tail;
132
133 assert_spin_locked(&fq->lock);
134
135 fq->tail = (idx + 1) & fq->mod_mask;
136
137 return idx;
138}
139
140static void fq_ring_free_locked(struct iommu_dma_cookie *cookie, struct iova_fq *fq)
141{
142 u64 counter = atomic64_read(&cookie->fq_flush_finish_cnt);
143 unsigned int idx;
144
145 assert_spin_locked(&fq->lock);
146
147 fq_ring_for_each(idx, fq) {
148
149 if (fq->entries[idx].counter >= counter)
150 break;
151
152 iommu_put_pages_list(&fq->entries[idx].freelist);
153 free_iova_fast(&cookie->iovad,
154 fq->entries[idx].iova_pfn,
155 fq->entries[idx].pages);
156
157 fq->head = (fq->head + 1) & fq->mod_mask;
158 }
159}
160
161static void fq_ring_free(struct iommu_dma_cookie *cookie, struct iova_fq *fq)
162{
163 unsigned long flags;
164
165 spin_lock_irqsave(&fq->lock, flags);
166 fq_ring_free_locked(cookie, fq);
167 spin_unlock_irqrestore(&fq->lock, flags);
168}
169
170static void fq_flush_iotlb(struct iommu_dma_cookie *cookie)
171{
172 atomic64_inc(&cookie->fq_flush_start_cnt);
173 cookie->fq_domain->ops->flush_iotlb_all(cookie->fq_domain);
174 atomic64_inc(&cookie->fq_flush_finish_cnt);
175}
176
177static void fq_flush_timeout(struct timer_list *t)
178{
179 struct iommu_dma_cookie *cookie = from_timer(cookie, t, fq_timer);
180 int cpu;
181
182 atomic_set(&cookie->fq_timer_on, 0);
183 fq_flush_iotlb(cookie);
184
185 if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE) {
186 fq_ring_free(cookie, cookie->single_fq);
187 } else {
188 for_each_possible_cpu(cpu)
189 fq_ring_free(cookie, per_cpu_ptr(cookie->percpu_fq, cpu));
190 }
191}
192
193static void queue_iova(struct iommu_dma_cookie *cookie,
194 unsigned long pfn, unsigned long pages,
195 struct list_head *freelist)
196{
197 struct iova_fq *fq;
198 unsigned long flags;
199 unsigned int idx;
200
201 /*
202 * Order against the IOMMU driver's pagetable update from unmapping
203 * @pte, to guarantee that fq_flush_iotlb() observes that if called
204 * from a different CPU before we release the lock below. Full barrier
205 * so it also pairs with iommu_dma_init_fq() to avoid seeing partially
206 * written fq state here.
207 */
208 smp_mb();
209
210 if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE)
211 fq = cookie->single_fq;
212 else
213 fq = raw_cpu_ptr(cookie->percpu_fq);
214
215 spin_lock_irqsave(&fq->lock, flags);
216
217 /*
218 * First remove all entries from the flush queue that have already been
219 * flushed out on another CPU. This makes the fq_full() check below less
220 * likely to be true.
221 */
222 fq_ring_free_locked(cookie, fq);
223
224 if (fq_full(fq)) {
225 fq_flush_iotlb(cookie);
226 fq_ring_free_locked(cookie, fq);
227 }
228
229 idx = fq_ring_add(fq);
230
231 fq->entries[idx].iova_pfn = pfn;
232 fq->entries[idx].pages = pages;
233 fq->entries[idx].counter = atomic64_read(&cookie->fq_flush_start_cnt);
234 list_splice(freelist, &fq->entries[idx].freelist);
235
236 spin_unlock_irqrestore(&fq->lock, flags);
237
238 /* Avoid false sharing as much as possible. */
239 if (!atomic_read(&cookie->fq_timer_on) &&
240 !atomic_xchg(&cookie->fq_timer_on, 1))
241 mod_timer(&cookie->fq_timer,
242 jiffies + msecs_to_jiffies(cookie->options.fq_timeout));
243}
244
245static void iommu_dma_free_fq_single(struct iova_fq *fq)
246{
247 int idx;
248
249 fq_ring_for_each(idx, fq)
250 iommu_put_pages_list(&fq->entries[idx].freelist);
251 vfree(fq);
252}
253
254static void iommu_dma_free_fq_percpu(struct iova_fq __percpu *percpu_fq)
255{
256 int cpu, idx;
257
258 /* The IOVAs will be torn down separately, so just free our queued pages */
259 for_each_possible_cpu(cpu) {
260 struct iova_fq *fq = per_cpu_ptr(percpu_fq, cpu);
261
262 fq_ring_for_each(idx, fq)
263 iommu_put_pages_list(&fq->entries[idx].freelist);
264 }
265
266 free_percpu(percpu_fq);
267}
268
269static void iommu_dma_free_fq(struct iommu_dma_cookie *cookie)
270{
271 if (!cookie->fq_domain)
272 return;
273
274 timer_delete_sync(&cookie->fq_timer);
275 if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE)
276 iommu_dma_free_fq_single(cookie->single_fq);
277 else
278 iommu_dma_free_fq_percpu(cookie->percpu_fq);
279}
280
281static void iommu_dma_init_one_fq(struct iova_fq *fq, size_t fq_size)
282{
283 int i;
284
285 fq->head = 0;
286 fq->tail = 0;
287 fq->mod_mask = fq_size - 1;
288
289 spin_lock_init(&fq->lock);
290
291 for (i = 0; i < fq_size; i++)
292 INIT_LIST_HEAD(&fq->entries[i].freelist);
293}
294
295static int iommu_dma_init_fq_single(struct iommu_dma_cookie *cookie)
296{
297 size_t fq_size = cookie->options.fq_size;
298 struct iova_fq *queue;
299
300 queue = vmalloc(struct_size(queue, entries, fq_size));
301 if (!queue)
302 return -ENOMEM;
303 iommu_dma_init_one_fq(queue, fq_size);
304 cookie->single_fq = queue;
305
306 return 0;
307}
308
309static int iommu_dma_init_fq_percpu(struct iommu_dma_cookie *cookie)
310{
311 size_t fq_size = cookie->options.fq_size;
312 struct iova_fq __percpu *queue;
313 int cpu;
314
315 queue = __alloc_percpu(struct_size(queue, entries, fq_size),
316 __alignof__(*queue));
317 if (!queue)
318 return -ENOMEM;
319
320 for_each_possible_cpu(cpu)
321 iommu_dma_init_one_fq(per_cpu_ptr(queue, cpu), fq_size);
322 cookie->percpu_fq = queue;
323 return 0;
324}
325
326/* sysfs updates are serialised by the mutex of the group owning @domain */
327int iommu_dma_init_fq(struct iommu_domain *domain)
328{
329 struct iommu_dma_cookie *cookie = domain->iova_cookie;
330 int rc;
331
332 if (cookie->fq_domain)
333 return 0;
334
335 atomic64_set(&cookie->fq_flush_start_cnt, 0);
336 atomic64_set(&cookie->fq_flush_finish_cnt, 0);
337
338 if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE)
339 rc = iommu_dma_init_fq_single(cookie);
340 else
341 rc = iommu_dma_init_fq_percpu(cookie);
342
343 if (rc) {
344 pr_warn("iova flush queue initialization failed\n");
345 return -ENOMEM;
346 }
347
348 timer_setup(&cookie->fq_timer, fq_flush_timeout, 0);
349 atomic_set(&cookie->fq_timer_on, 0);
350 /*
351 * Prevent incomplete fq state being observable. Pairs with path from
352 * __iommu_dma_unmap() through iommu_dma_free_iova() to queue_iova()
353 */
354 smp_wmb();
355 WRITE_ONCE(cookie->fq_domain, domain);
356 return 0;
357}
358
359/**
360 * iommu_get_dma_cookie - Acquire DMA-API resources for a domain
361 * @domain: IOMMU domain to prepare for DMA-API usage
362 */
363int iommu_get_dma_cookie(struct iommu_domain *domain)
364{
365 struct iommu_dma_cookie *cookie;
366
367 if (domain->cookie_type != IOMMU_COOKIE_NONE)
368 return -EEXIST;
369
370 cookie = kzalloc(sizeof(*cookie), GFP_KERNEL);
371 if (!cookie)
372 return -ENOMEM;
373
374 INIT_LIST_HEAD(&cookie->msi_page_list);
375 domain->cookie_type = IOMMU_COOKIE_DMA_IOVA;
376 domain->iova_cookie = cookie;
377 return 0;
378}
379
380/**
381 * iommu_get_msi_cookie - Acquire just MSI remapping resources
382 * @domain: IOMMU domain to prepare
383 * @base: Start address of IOVA region for MSI mappings
384 *
385 * Users who manage their own IOVA allocation and do not want DMA API support,
386 * but would still like to take advantage of automatic MSI remapping, can use
387 * this to initialise their own domain appropriately. Users should reserve a
388 * contiguous IOVA region, starting at @base, large enough to accommodate the
389 * number of PAGE_SIZE mappings necessary to cover every MSI doorbell address
390 * used by the devices attached to @domain.
391 */
392int iommu_get_msi_cookie(struct iommu_domain *domain, dma_addr_t base)
393{
394 struct iommu_dma_msi_cookie *cookie;
395
396 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
397 return -EINVAL;
398
399 if (domain->cookie_type != IOMMU_COOKIE_NONE)
400 return -EEXIST;
401
402 cookie = kzalloc(sizeof(*cookie), GFP_KERNEL);
403 if (!cookie)
404 return -ENOMEM;
405
406 cookie->msi_iova = base;
407 INIT_LIST_HEAD(&cookie->msi_page_list);
408 domain->cookie_type = IOMMU_COOKIE_DMA_MSI;
409 domain->msi_cookie = cookie;
410 return 0;
411}
412EXPORT_SYMBOL(iommu_get_msi_cookie);
413
414/**
415 * iommu_put_dma_cookie - Release a domain's DMA mapping resources
416 * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie()
417 */
418void iommu_put_dma_cookie(struct iommu_domain *domain)
419{
420 struct iommu_dma_cookie *cookie = domain->iova_cookie;
421 struct iommu_dma_msi_page *msi, *tmp;
422
423 if (cookie->iovad.granule) {
424 iommu_dma_free_fq(cookie);
425 put_iova_domain(&cookie->iovad);
426 }
427 list_for_each_entry_safe(msi, tmp, &cookie->msi_page_list, list)
428 kfree(msi);
429 kfree(cookie);
430}
431
432/**
433 * iommu_put_msi_cookie - Release a domain's MSI mapping resources
434 * @domain: IOMMU domain previously prepared by iommu_get_msi_cookie()
435 */
436void iommu_put_msi_cookie(struct iommu_domain *domain)
437{
438 struct iommu_dma_msi_cookie *cookie = domain->msi_cookie;
439 struct iommu_dma_msi_page *msi, *tmp;
440
441 list_for_each_entry_safe(msi, tmp, &cookie->msi_page_list, list)
442 kfree(msi);
443 kfree(cookie);
444}
445
446/**
447 * iommu_dma_get_resv_regions - Reserved region driver helper
448 * @dev: Device from iommu_get_resv_regions()
449 * @list: Reserved region list from iommu_get_resv_regions()
450 *
451 * IOMMU drivers can use this to implement their .get_resv_regions callback
452 * for general non-IOMMU-specific reservations. Currently, this covers GICv3
453 * ITS region reservation on ACPI based ARM platforms that may require HW MSI
454 * reservation.
455 */
456void iommu_dma_get_resv_regions(struct device *dev, struct list_head *list)
457{
458
459 if (!is_of_node(dev_iommu_fwspec_get(dev)->iommu_fwnode))
460 iort_iommu_get_resv_regions(dev, list);
461
462 if (dev->of_node)
463 of_iommu_get_resv_regions(dev, list);
464}
465EXPORT_SYMBOL(iommu_dma_get_resv_regions);
466
467static int cookie_init_hw_msi_region(struct iommu_dma_cookie *cookie,
468 phys_addr_t start, phys_addr_t end)
469{
470 struct iova_domain *iovad = &cookie->iovad;
471 struct iommu_dma_msi_page *msi_page;
472 int i, num_pages;
473
474 start -= iova_offset(iovad, start);
475 num_pages = iova_align(iovad, end - start) >> iova_shift(iovad);
476
477 for (i = 0; i < num_pages; i++) {
478 msi_page = kmalloc(sizeof(*msi_page), GFP_KERNEL);
479 if (!msi_page)
480 return -ENOMEM;
481
482 msi_page->phys = start;
483 msi_page->iova = start;
484 INIT_LIST_HEAD(&msi_page->list);
485 list_add(&msi_page->list, &cookie->msi_page_list);
486 start += iovad->granule;
487 }
488
489 return 0;
490}
491
492static int iommu_dma_ranges_sort(void *priv, const struct list_head *a,
493 const struct list_head *b)
494{
495 struct resource_entry *res_a = list_entry(a, typeof(*res_a), node);
496 struct resource_entry *res_b = list_entry(b, typeof(*res_b), node);
497
498 return res_a->res->start > res_b->res->start;
499}
500
501static int iova_reserve_pci_windows(struct pci_dev *dev,
502 struct iova_domain *iovad)
503{
504 struct pci_host_bridge *bridge = pci_find_host_bridge(dev->bus);
505 struct resource_entry *window;
506 unsigned long lo, hi;
507 phys_addr_t start = 0, end;
508
509 resource_list_for_each_entry(window, &bridge->windows) {
510 if (resource_type(window->res) != IORESOURCE_MEM)
511 continue;
512
513 lo = iova_pfn(iovad, window->res->start - window->offset);
514 hi = iova_pfn(iovad, window->res->end - window->offset);
515 reserve_iova(iovad, lo, hi);
516 }
517
518 /* Get reserved DMA windows from host bridge */
519 list_sort(NULL, &bridge->dma_ranges, iommu_dma_ranges_sort);
520 resource_list_for_each_entry(window, &bridge->dma_ranges) {
521 end = window->res->start - window->offset;
522resv_iova:
523 if (end > start) {
524 lo = iova_pfn(iovad, start);
525 hi = iova_pfn(iovad, end);
526 reserve_iova(iovad, lo, hi);
527 } else if (end < start) {
528 /* DMA ranges should be non-overlapping */
529 dev_err(&dev->dev,
530 "Failed to reserve IOVA [%pa-%pa]\n",
531 &start, &end);
532 return -EINVAL;
533 }
534
535 start = window->res->end - window->offset + 1;
536 /* If window is last entry */
537 if (window->node.next == &bridge->dma_ranges &&
538 end != ~(phys_addr_t)0) {
539 end = ~(phys_addr_t)0;
540 goto resv_iova;
541 }
542 }
543
544 return 0;
545}
546
547static int iova_reserve_iommu_regions(struct device *dev,
548 struct iommu_domain *domain)
549{
550 struct iommu_dma_cookie *cookie = domain->iova_cookie;
551 struct iova_domain *iovad = &cookie->iovad;
552 struct iommu_resv_region *region;
553 LIST_HEAD(resv_regions);
554 int ret = 0;
555
556 if (dev_is_pci(dev)) {
557 ret = iova_reserve_pci_windows(to_pci_dev(dev), iovad);
558 if (ret)
559 return ret;
560 }
561
562 iommu_get_resv_regions(dev, &resv_regions);
563 list_for_each_entry(region, &resv_regions, list) {
564 unsigned long lo, hi;
565
566 /* We ARE the software that manages these! */
567 if (region->type == IOMMU_RESV_SW_MSI)
568 continue;
569
570 lo = iova_pfn(iovad, region->start);
571 hi = iova_pfn(iovad, region->start + region->length - 1);
572 reserve_iova(iovad, lo, hi);
573
574 if (region->type == IOMMU_RESV_MSI)
575 ret = cookie_init_hw_msi_region(cookie, region->start,
576 region->start + region->length);
577 if (ret)
578 break;
579 }
580 iommu_put_resv_regions(dev, &resv_regions);
581
582 return ret;
583}
584
585static bool dev_is_untrusted(struct device *dev)
586{
587 return dev_is_pci(dev) && to_pci_dev(dev)->untrusted;
588}
589
590static bool dev_use_swiotlb(struct device *dev, size_t size,
591 enum dma_data_direction dir)
592{
593 return IS_ENABLED(CONFIG_SWIOTLB) &&
594 (dev_is_untrusted(dev) ||
595 dma_kmalloc_needs_bounce(dev, size, dir));
596}
597
598static bool dev_use_sg_swiotlb(struct device *dev, struct scatterlist *sg,
599 int nents, enum dma_data_direction dir)
600{
601 struct scatterlist *s;
602 int i;
603
604 if (!IS_ENABLED(CONFIG_SWIOTLB))
605 return false;
606
607 if (dev_is_untrusted(dev))
608 return true;
609
610 /*
611 * If kmalloc() buffers are not DMA-safe for this device and
612 * direction, check the individual lengths in the sg list. If any
613 * element is deemed unsafe, use the swiotlb for bouncing.
614 */
615 if (!dma_kmalloc_safe(dev, dir)) {
616 for_each_sg(sg, s, nents, i)
617 if (!dma_kmalloc_size_aligned(s->length))
618 return true;
619 }
620
621 return false;
622}
623
624/**
625 * iommu_dma_init_options - Initialize dma-iommu options
626 * @options: The options to be initialized
627 * @dev: Device the options are set for
628 *
629 * This allows tuning dma-iommu specific to device properties
630 */
631static void iommu_dma_init_options(struct iommu_dma_options *options,
632 struct device *dev)
633{
634 /* Shadowing IOTLB flushes do better with a single large queue */
635 if (dev->iommu->shadow_on_flush) {
636 options->qt = IOMMU_DMA_OPTS_SINGLE_QUEUE;
637 options->fq_timeout = IOVA_SINGLE_FQ_TIMEOUT;
638 options->fq_size = IOVA_SINGLE_FQ_SIZE;
639 } else {
640 options->qt = IOMMU_DMA_OPTS_PER_CPU_QUEUE;
641 options->fq_size = IOVA_DEFAULT_FQ_SIZE;
642 options->fq_timeout = IOVA_DEFAULT_FQ_TIMEOUT;
643 }
644}
645
646/**
647 * iommu_dma_init_domain - Initialise a DMA mapping domain
648 * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie()
649 * @dev: Device the domain is being initialised for
650 *
651 * If the geometry and dma_range_map include address 0, we reserve that page
652 * to ensure it is an invalid IOVA. It is safe to reinitialise a domain, but
653 * any change which could make prior IOVAs invalid will fail.
654 */
655static int iommu_dma_init_domain(struct iommu_domain *domain, struct device *dev)
656{
657 struct iommu_dma_cookie *cookie = domain->iova_cookie;
658 const struct bus_dma_region *map = dev->dma_range_map;
659 unsigned long order, base_pfn;
660 struct iova_domain *iovad;
661 int ret;
662
663 if (!cookie || domain->cookie_type != IOMMU_COOKIE_DMA_IOVA)
664 return -EINVAL;
665
666 iovad = &cookie->iovad;
667
668 /* Use the smallest supported page size for IOVA granularity */
669 order = __ffs(domain->pgsize_bitmap);
670 base_pfn = 1;
671
672 /* Check the domain allows at least some access to the device... */
673 if (map) {
674 if (dma_range_map_min(map) > domain->geometry.aperture_end ||
675 dma_range_map_max(map) < domain->geometry.aperture_start) {
676 pr_warn("specified DMA range outside IOMMU capability\n");
677 return -EFAULT;
678 }
679 }
680 /* ...then finally give it a kicking to make sure it fits */
681 base_pfn = max_t(unsigned long, base_pfn,
682 domain->geometry.aperture_start >> order);
683
684 /* start_pfn is always nonzero for an already-initialised domain */
685 if (iovad->start_pfn) {
686 if (1UL << order != iovad->granule ||
687 base_pfn != iovad->start_pfn) {
688 pr_warn("Incompatible range for DMA domain\n");
689 return -EFAULT;
690 }
691
692 return 0;
693 }
694
695 init_iova_domain(iovad, 1UL << order, base_pfn);
696 ret = iova_domain_init_rcaches(iovad);
697 if (ret)
698 return ret;
699
700 iommu_dma_init_options(&cookie->options, dev);
701
702 /* If the FQ fails we can simply fall back to strict mode */
703 if (domain->type == IOMMU_DOMAIN_DMA_FQ &&
704 (!device_iommu_capable(dev, IOMMU_CAP_DEFERRED_FLUSH) || iommu_dma_init_fq(domain)))
705 domain->type = IOMMU_DOMAIN_DMA;
706
707 return iova_reserve_iommu_regions(dev, domain);
708}
709
710/**
711 * dma_info_to_prot - Translate DMA API directions and attributes to IOMMU API
712 * page flags.
713 * @dir: Direction of DMA transfer
714 * @coherent: Is the DMA master cache-coherent?
715 * @attrs: DMA attributes for the mapping
716 *
717 * Return: corresponding IOMMU API page protection flags
718 */
719static int dma_info_to_prot(enum dma_data_direction dir, bool coherent,
720 unsigned long attrs)
721{
722 int prot = coherent ? IOMMU_CACHE : 0;
723
724 if (attrs & DMA_ATTR_PRIVILEGED)
725 prot |= IOMMU_PRIV;
726
727 switch (dir) {
728 case DMA_BIDIRECTIONAL:
729 return prot | IOMMU_READ | IOMMU_WRITE;
730 case DMA_TO_DEVICE:
731 return prot | IOMMU_READ;
732 case DMA_FROM_DEVICE:
733 return prot | IOMMU_WRITE;
734 default:
735 return 0;
736 }
737}
738
739static dma_addr_t iommu_dma_alloc_iova(struct iommu_domain *domain,
740 size_t size, u64 dma_limit, struct device *dev)
741{
742 struct iommu_dma_cookie *cookie = domain->iova_cookie;
743 struct iova_domain *iovad = &cookie->iovad;
744 unsigned long shift, iova_len, iova;
745
746 if (domain->cookie_type == IOMMU_COOKIE_DMA_MSI) {
747 domain->msi_cookie->msi_iova += size;
748 return domain->msi_cookie->msi_iova - size;
749 }
750
751 shift = iova_shift(iovad);
752 iova_len = size >> shift;
753
754 dma_limit = min_not_zero(dma_limit, dev->bus_dma_limit);
755
756 if (domain->geometry.force_aperture)
757 dma_limit = min(dma_limit, (u64)domain->geometry.aperture_end);
758
759 /*
760 * Try to use all the 32-bit PCI addresses first. The original SAC vs.
761 * DAC reasoning loses relevance with PCIe, but enough hardware and
762 * firmware bugs are still lurking out there that it's safest not to
763 * venture into the 64-bit space until necessary.
764 *
765 * If your device goes wrong after seeing the notice then likely either
766 * its driver is not setting DMA masks accurately, the hardware has
767 * some inherent bug in handling >32-bit addresses, or not all the
768 * expected address bits are wired up between the device and the IOMMU.
769 */
770 if (dma_limit > DMA_BIT_MASK(32) && dev->iommu->pci_32bit_workaround) {
771 iova = alloc_iova_fast(iovad, iova_len,
772 DMA_BIT_MASK(32) >> shift, false);
773 if (iova)
774 goto done;
775
776 dev->iommu->pci_32bit_workaround = false;
777 dev_notice(dev, "Using %d-bit DMA addresses\n", bits_per(dma_limit));
778 }
779
780 iova = alloc_iova_fast(iovad, iova_len, dma_limit >> shift, true);
781done:
782 return (dma_addr_t)iova << shift;
783}
784
785static void iommu_dma_free_iova(struct iommu_domain *domain, dma_addr_t iova,
786 size_t size, struct iommu_iotlb_gather *gather)
787{
788 struct iova_domain *iovad = &domain->iova_cookie->iovad;
789
790 /* The MSI case is only ever cleaning up its most recent allocation */
791 if (domain->cookie_type == IOMMU_COOKIE_DMA_MSI)
792 domain->msi_cookie->msi_iova -= size;
793 else if (gather && gather->queued)
794 queue_iova(domain->iova_cookie, iova_pfn(iovad, iova),
795 size >> iova_shift(iovad),
796 &gather->freelist);
797 else
798 free_iova_fast(iovad, iova_pfn(iovad, iova),
799 size >> iova_shift(iovad));
800}
801
802static void __iommu_dma_unmap(struct device *dev, dma_addr_t dma_addr,
803 size_t size)
804{
805 struct iommu_domain *domain = iommu_get_dma_domain(dev);
806 struct iommu_dma_cookie *cookie = domain->iova_cookie;
807 struct iova_domain *iovad = &cookie->iovad;
808 size_t iova_off = iova_offset(iovad, dma_addr);
809 struct iommu_iotlb_gather iotlb_gather;
810 size_t unmapped;
811
812 dma_addr -= iova_off;
813 size = iova_align(iovad, size + iova_off);
814 iommu_iotlb_gather_init(&iotlb_gather);
815 iotlb_gather.queued = READ_ONCE(cookie->fq_domain);
816
817 unmapped = iommu_unmap_fast(domain, dma_addr, size, &iotlb_gather);
818 WARN_ON(unmapped != size);
819
820 if (!iotlb_gather.queued)
821 iommu_iotlb_sync(domain, &iotlb_gather);
822 iommu_dma_free_iova(domain, dma_addr, size, &iotlb_gather);
823}
824
825static dma_addr_t __iommu_dma_map(struct device *dev, phys_addr_t phys,
826 size_t size, int prot, u64 dma_mask)
827{
828 struct iommu_domain *domain = iommu_get_dma_domain(dev);
829 struct iommu_dma_cookie *cookie = domain->iova_cookie;
830 struct iova_domain *iovad = &cookie->iovad;
831 size_t iova_off = iova_offset(iovad, phys);
832 dma_addr_t iova;
833
834 if (static_branch_unlikely(&iommu_deferred_attach_enabled) &&
835 iommu_deferred_attach(dev, domain))
836 return DMA_MAPPING_ERROR;
837
838 /* If anyone ever wants this we'd need support in the IOVA allocator */
839 if (dev_WARN_ONCE(dev, dma_get_min_align_mask(dev) > iova_mask(iovad),
840 "Unsupported alignment constraint\n"))
841 return DMA_MAPPING_ERROR;
842
843 size = iova_align(iovad, size + iova_off);
844
845 iova = iommu_dma_alloc_iova(domain, size, dma_mask, dev);
846 if (!iova)
847 return DMA_MAPPING_ERROR;
848
849 if (iommu_map(domain, iova, phys - iova_off, size, prot, GFP_ATOMIC)) {
850 iommu_dma_free_iova(domain, iova, size, NULL);
851 return DMA_MAPPING_ERROR;
852 }
853 return iova + iova_off;
854}
855
856static void __iommu_dma_free_pages(struct page **pages, int count)
857{
858 while (count--)
859 __free_page(pages[count]);
860 kvfree(pages);
861}
862
863static struct page **__iommu_dma_alloc_pages(struct device *dev,
864 unsigned int count, unsigned long order_mask, gfp_t gfp)
865{
866 struct page **pages;
867 unsigned int i = 0, nid = dev_to_node(dev);
868
869 order_mask &= GENMASK(MAX_PAGE_ORDER, 0);
870 if (!order_mask)
871 return NULL;
872
873 pages = kvcalloc(count, sizeof(*pages), GFP_KERNEL);
874 if (!pages)
875 return NULL;
876
877 /* IOMMU can map any pages, so himem can also be used here */
878 gfp |= __GFP_NOWARN | __GFP_HIGHMEM;
879
880 while (count) {
881 struct page *page = NULL;
882 unsigned int order_size;
883
884 /*
885 * Higher-order allocations are a convenience rather
886 * than a necessity, hence using __GFP_NORETRY until
887 * falling back to minimum-order allocations.
888 */
889 for (order_mask &= GENMASK(__fls(count), 0);
890 order_mask; order_mask &= ~order_size) {
891 unsigned int order = __fls(order_mask);
892 gfp_t alloc_flags = gfp;
893
894 order_size = 1U << order;
895 if (order_mask > order_size)
896 alloc_flags |= __GFP_NORETRY;
897 page = alloc_pages_node(nid, alloc_flags, order);
898 if (!page)
899 continue;
900 if (order)
901 split_page(page, order);
902 break;
903 }
904 if (!page) {
905 __iommu_dma_free_pages(pages, i);
906 return NULL;
907 }
908 count -= order_size;
909 while (order_size--)
910 pages[i++] = page++;
911 }
912 return pages;
913}
914
915/*
916 * If size is less than PAGE_SIZE, then a full CPU page will be allocated,
917 * but an IOMMU which supports smaller pages might not map the whole thing.
918 */
919static struct page **__iommu_dma_alloc_noncontiguous(struct device *dev,
920 size_t size, struct sg_table *sgt, gfp_t gfp, unsigned long attrs)
921{
922 struct iommu_domain *domain = iommu_get_dma_domain(dev);
923 struct iommu_dma_cookie *cookie = domain->iova_cookie;
924 struct iova_domain *iovad = &cookie->iovad;
925 bool coherent = dev_is_dma_coherent(dev);
926 int ioprot = dma_info_to_prot(DMA_BIDIRECTIONAL, coherent, attrs);
927 unsigned int count, min_size, alloc_sizes = domain->pgsize_bitmap;
928 struct page **pages;
929 dma_addr_t iova;
930 ssize_t ret;
931
932 if (static_branch_unlikely(&iommu_deferred_attach_enabled) &&
933 iommu_deferred_attach(dev, domain))
934 return NULL;
935
936 min_size = alloc_sizes & -alloc_sizes;
937 if (min_size < PAGE_SIZE) {
938 min_size = PAGE_SIZE;
939 alloc_sizes |= PAGE_SIZE;
940 } else {
941 size = ALIGN(size, min_size);
942 }
943 if (attrs & DMA_ATTR_ALLOC_SINGLE_PAGES)
944 alloc_sizes = min_size;
945
946 count = PAGE_ALIGN(size) >> PAGE_SHIFT;
947 pages = __iommu_dma_alloc_pages(dev, count, alloc_sizes >> PAGE_SHIFT,
948 gfp);
949 if (!pages)
950 return NULL;
951
952 size = iova_align(iovad, size);
953 iova = iommu_dma_alloc_iova(domain, size, dev->coherent_dma_mask, dev);
954 if (!iova)
955 goto out_free_pages;
956
957 /*
958 * Remove the zone/policy flags from the GFP - these are applied to the
959 * __iommu_dma_alloc_pages() but are not used for the supporting
960 * internal allocations that follow.
961 */
962 gfp &= ~(__GFP_DMA | __GFP_DMA32 | __GFP_HIGHMEM | __GFP_COMP);
963
964 if (sg_alloc_table_from_pages(sgt, pages, count, 0, size, gfp))
965 goto out_free_iova;
966
967 if (!(ioprot & IOMMU_CACHE)) {
968 struct scatterlist *sg;
969 int i;
970
971 for_each_sg(sgt->sgl, sg, sgt->orig_nents, i)
972 arch_dma_prep_coherent(sg_page(sg), sg->length);
973 }
974
975 ret = iommu_map_sg(domain, iova, sgt->sgl, sgt->orig_nents, ioprot,
976 gfp);
977 if (ret < 0 || ret < size)
978 goto out_free_sg;
979
980 sgt->sgl->dma_address = iova;
981 sgt->sgl->dma_length = size;
982 return pages;
983
984out_free_sg:
985 sg_free_table(sgt);
986out_free_iova:
987 iommu_dma_free_iova(domain, iova, size, NULL);
988out_free_pages:
989 __iommu_dma_free_pages(pages, count);
990 return NULL;
991}
992
993static void *iommu_dma_alloc_remap(struct device *dev, size_t size,
994 dma_addr_t *dma_handle, gfp_t gfp, unsigned long attrs)
995{
996 struct page **pages;
997 struct sg_table sgt;
998 void *vaddr;
999 pgprot_t prot = dma_pgprot(dev, PAGE_KERNEL, attrs);
1000
1001 pages = __iommu_dma_alloc_noncontiguous(dev, size, &sgt, gfp, attrs);
1002 if (!pages)
1003 return NULL;
1004 *dma_handle = sgt.sgl->dma_address;
1005 sg_free_table(&sgt);
1006 vaddr = dma_common_pages_remap(pages, size, prot,
1007 __builtin_return_address(0));
1008 if (!vaddr)
1009 goto out_unmap;
1010 return vaddr;
1011
1012out_unmap:
1013 __iommu_dma_unmap(dev, *dma_handle, size);
1014 __iommu_dma_free_pages(pages, PAGE_ALIGN(size) >> PAGE_SHIFT);
1015 return NULL;
1016}
1017
1018/*
1019 * This is the actual return value from the iommu_dma_alloc_noncontiguous.
1020 *
1021 * The users of the DMA API should only care about the sg_table, but to make
1022 * the DMA-API internal vmaping and freeing easier we stash away the page
1023 * array as well (except for the fallback case). This can go away any time,
1024 * e.g. when a vmap-variant that takes a scatterlist comes along.
1025 */
1026struct dma_sgt_handle {
1027 struct sg_table sgt;
1028 struct page **pages;
1029};
1030#define sgt_handle(sgt) \
1031 container_of((sgt), struct dma_sgt_handle, sgt)
1032
1033struct sg_table *iommu_dma_alloc_noncontiguous(struct device *dev, size_t size,
1034 enum dma_data_direction dir, gfp_t gfp, unsigned long attrs)
1035{
1036 struct dma_sgt_handle *sh;
1037
1038 sh = kmalloc(sizeof(*sh), gfp);
1039 if (!sh)
1040 return NULL;
1041
1042 sh->pages = __iommu_dma_alloc_noncontiguous(dev, size, &sh->sgt, gfp, attrs);
1043 if (!sh->pages) {
1044 kfree(sh);
1045 return NULL;
1046 }
1047 return &sh->sgt;
1048}
1049
1050void iommu_dma_free_noncontiguous(struct device *dev, size_t size,
1051 struct sg_table *sgt, enum dma_data_direction dir)
1052{
1053 struct dma_sgt_handle *sh = sgt_handle(sgt);
1054
1055 __iommu_dma_unmap(dev, sgt->sgl->dma_address, size);
1056 __iommu_dma_free_pages(sh->pages, PAGE_ALIGN(size) >> PAGE_SHIFT);
1057 sg_free_table(&sh->sgt);
1058 kfree(sh);
1059}
1060
1061void *iommu_dma_vmap_noncontiguous(struct device *dev, size_t size,
1062 struct sg_table *sgt)
1063{
1064 unsigned long count = PAGE_ALIGN(size) >> PAGE_SHIFT;
1065
1066 return vmap(sgt_handle(sgt)->pages, count, VM_MAP, PAGE_KERNEL);
1067}
1068
1069int iommu_dma_mmap_noncontiguous(struct device *dev, struct vm_area_struct *vma,
1070 size_t size, struct sg_table *sgt)
1071{
1072 unsigned long count = PAGE_ALIGN(size) >> PAGE_SHIFT;
1073
1074 if (vma->vm_pgoff >= count || vma_pages(vma) > count - vma->vm_pgoff)
1075 return -ENXIO;
1076 return vm_map_pages(vma, sgt_handle(sgt)->pages, count);
1077}
1078
1079void iommu_dma_sync_single_for_cpu(struct device *dev, dma_addr_t dma_handle,
1080 size_t size, enum dma_data_direction dir)
1081{
1082 phys_addr_t phys;
1083
1084 if (dev_is_dma_coherent(dev) && !dev_use_swiotlb(dev, size, dir))
1085 return;
1086
1087 phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle);
1088 if (!dev_is_dma_coherent(dev))
1089 arch_sync_dma_for_cpu(phys, size, dir);
1090
1091 swiotlb_sync_single_for_cpu(dev, phys, size, dir);
1092}
1093
1094void iommu_dma_sync_single_for_device(struct device *dev, dma_addr_t dma_handle,
1095 size_t size, enum dma_data_direction dir)
1096{
1097 phys_addr_t phys;
1098
1099 if (dev_is_dma_coherent(dev) && !dev_use_swiotlb(dev, size, dir))
1100 return;
1101
1102 phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle);
1103 swiotlb_sync_single_for_device(dev, phys, size, dir);
1104
1105 if (!dev_is_dma_coherent(dev))
1106 arch_sync_dma_for_device(phys, size, dir);
1107}
1108
1109void iommu_dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sgl,
1110 int nelems, enum dma_data_direction dir)
1111{
1112 struct scatterlist *sg;
1113 int i;
1114
1115 if (sg_dma_is_swiotlb(sgl))
1116 for_each_sg(sgl, sg, nelems, i)
1117 iommu_dma_sync_single_for_cpu(dev, sg_dma_address(sg),
1118 sg->length, dir);
1119 else if (!dev_is_dma_coherent(dev))
1120 for_each_sg(sgl, sg, nelems, i)
1121 arch_sync_dma_for_cpu(sg_phys(sg), sg->length, dir);
1122}
1123
1124void iommu_dma_sync_sg_for_device(struct device *dev, struct scatterlist *sgl,
1125 int nelems, enum dma_data_direction dir)
1126{
1127 struct scatterlist *sg;
1128 int i;
1129
1130 if (sg_dma_is_swiotlb(sgl))
1131 for_each_sg(sgl, sg, nelems, i)
1132 iommu_dma_sync_single_for_device(dev,
1133 sg_dma_address(sg),
1134 sg->length, dir);
1135 else if (!dev_is_dma_coherent(dev))
1136 for_each_sg(sgl, sg, nelems, i)
1137 arch_sync_dma_for_device(sg_phys(sg), sg->length, dir);
1138}
1139
1140dma_addr_t iommu_dma_map_page(struct device *dev, struct page *page,
1141 unsigned long offset, size_t size, enum dma_data_direction dir,
1142 unsigned long attrs)
1143{
1144 phys_addr_t phys = page_to_phys(page) + offset;
1145 bool coherent = dev_is_dma_coherent(dev);
1146 int prot = dma_info_to_prot(dir, coherent, attrs);
1147 struct iommu_domain *domain = iommu_get_dma_domain(dev);
1148 struct iommu_dma_cookie *cookie = domain->iova_cookie;
1149 struct iova_domain *iovad = &cookie->iovad;
1150 dma_addr_t iova, dma_mask = dma_get_mask(dev);
1151
1152 /*
1153 * If both the physical buffer start address and size are
1154 * page aligned, we don't need to use a bounce page.
1155 */
1156 if (dev_use_swiotlb(dev, size, dir) &&
1157 iova_offset(iovad, phys | size)) {
1158 if (!is_swiotlb_active(dev)) {
1159 dev_warn_once(dev, "DMA bounce buffers are inactive, unable to map unaligned transaction.\n");
1160 return DMA_MAPPING_ERROR;
1161 }
1162
1163 trace_swiotlb_bounced(dev, phys, size);
1164
1165 phys = swiotlb_tbl_map_single(dev, phys, size,
1166 iova_mask(iovad), dir, attrs);
1167
1168 if (phys == DMA_MAPPING_ERROR)
1169 return DMA_MAPPING_ERROR;
1170
1171 /*
1172 * Untrusted devices should not see padding areas with random
1173 * leftover kernel data, so zero the pre- and post-padding.
1174 * swiotlb_tbl_map_single() has initialized the bounce buffer
1175 * proper to the contents of the original memory buffer.
1176 */
1177 if (dev_is_untrusted(dev)) {
1178 size_t start, virt = (size_t)phys_to_virt(phys);
1179
1180 /* Pre-padding */
1181 start = iova_align_down(iovad, virt);
1182 memset((void *)start, 0, virt - start);
1183
1184 /* Post-padding */
1185 start = virt + size;
1186 memset((void *)start, 0,
1187 iova_align(iovad, start) - start);
1188 }
1189 }
1190
1191 if (!coherent && !(attrs & DMA_ATTR_SKIP_CPU_SYNC))
1192 arch_sync_dma_for_device(phys, size, dir);
1193
1194 iova = __iommu_dma_map(dev, phys, size, prot, dma_mask);
1195 if (iova == DMA_MAPPING_ERROR)
1196 swiotlb_tbl_unmap_single(dev, phys, size, dir, attrs);
1197 return iova;
1198}
1199
1200void iommu_dma_unmap_page(struct device *dev, dma_addr_t dma_handle,
1201 size_t size, enum dma_data_direction dir, unsigned long attrs)
1202{
1203 struct iommu_domain *domain = iommu_get_dma_domain(dev);
1204 phys_addr_t phys;
1205
1206 phys = iommu_iova_to_phys(domain, dma_handle);
1207 if (WARN_ON(!phys))
1208 return;
1209
1210 if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) && !dev_is_dma_coherent(dev))
1211 arch_sync_dma_for_cpu(phys, size, dir);
1212
1213 __iommu_dma_unmap(dev, dma_handle, size);
1214
1215 swiotlb_tbl_unmap_single(dev, phys, size, dir, attrs);
1216}
1217
1218/*
1219 * Prepare a successfully-mapped scatterlist to give back to the caller.
1220 *
1221 * At this point the segments are already laid out by iommu_dma_map_sg() to
1222 * avoid individually crossing any boundaries, so we merely need to check a
1223 * segment's start address to avoid concatenating across one.
1224 */
1225static int __finalise_sg(struct device *dev, struct scatterlist *sg, int nents,
1226 dma_addr_t dma_addr)
1227{
1228 struct scatterlist *s, *cur = sg;
1229 unsigned long seg_mask = dma_get_seg_boundary(dev);
1230 unsigned int cur_len = 0, max_len = dma_get_max_seg_size(dev);
1231 int i, count = 0;
1232
1233 for_each_sg(sg, s, nents, i) {
1234 /* Restore this segment's original unaligned fields first */
1235 dma_addr_t s_dma_addr = sg_dma_address(s);
1236 unsigned int s_iova_off = sg_dma_address(s);
1237 unsigned int s_length = sg_dma_len(s);
1238 unsigned int s_iova_len = s->length;
1239
1240 sg_dma_address(s) = DMA_MAPPING_ERROR;
1241 sg_dma_len(s) = 0;
1242
1243 if (sg_dma_is_bus_address(s)) {
1244 if (i > 0)
1245 cur = sg_next(cur);
1246
1247 sg_dma_unmark_bus_address(s);
1248 sg_dma_address(cur) = s_dma_addr;
1249 sg_dma_len(cur) = s_length;
1250 sg_dma_mark_bus_address(cur);
1251 count++;
1252 cur_len = 0;
1253 continue;
1254 }
1255
1256 s->offset += s_iova_off;
1257 s->length = s_length;
1258
1259 /*
1260 * Now fill in the real DMA data. If...
1261 * - there is a valid output segment to append to
1262 * - and this segment starts on an IOVA page boundary
1263 * - but doesn't fall at a segment boundary
1264 * - and wouldn't make the resulting output segment too long
1265 */
1266 if (cur_len && !s_iova_off && (dma_addr & seg_mask) &&
1267 (max_len - cur_len >= s_length)) {
1268 /* ...then concatenate it with the previous one */
1269 cur_len += s_length;
1270 } else {
1271 /* Otherwise start the next output segment */
1272 if (i > 0)
1273 cur = sg_next(cur);
1274 cur_len = s_length;
1275 count++;
1276
1277 sg_dma_address(cur) = dma_addr + s_iova_off;
1278 }
1279
1280 sg_dma_len(cur) = cur_len;
1281 dma_addr += s_iova_len;
1282
1283 if (s_length + s_iova_off < s_iova_len)
1284 cur_len = 0;
1285 }
1286 return count;
1287}
1288
1289/*
1290 * If mapping failed, then just restore the original list,
1291 * but making sure the DMA fields are invalidated.
1292 */
1293static void __invalidate_sg(struct scatterlist *sg, int nents)
1294{
1295 struct scatterlist *s;
1296 int i;
1297
1298 for_each_sg(sg, s, nents, i) {
1299 if (sg_dma_is_bus_address(s)) {
1300 sg_dma_unmark_bus_address(s);
1301 } else {
1302 if (sg_dma_address(s) != DMA_MAPPING_ERROR)
1303 s->offset += sg_dma_address(s);
1304 if (sg_dma_len(s))
1305 s->length = sg_dma_len(s);
1306 }
1307 sg_dma_address(s) = DMA_MAPPING_ERROR;
1308 sg_dma_len(s) = 0;
1309 }
1310}
1311
1312static void iommu_dma_unmap_sg_swiotlb(struct device *dev, struct scatterlist *sg,
1313 int nents, enum dma_data_direction dir, unsigned long attrs)
1314{
1315 struct scatterlist *s;
1316 int i;
1317
1318 for_each_sg(sg, s, nents, i)
1319 iommu_dma_unmap_page(dev, sg_dma_address(s),
1320 sg_dma_len(s), dir, attrs);
1321}
1322
1323static int iommu_dma_map_sg_swiotlb(struct device *dev, struct scatterlist *sg,
1324 int nents, enum dma_data_direction dir, unsigned long attrs)
1325{
1326 struct scatterlist *s;
1327 int i;
1328
1329 sg_dma_mark_swiotlb(sg);
1330
1331 for_each_sg(sg, s, nents, i) {
1332 sg_dma_address(s) = iommu_dma_map_page(dev, sg_page(s),
1333 s->offset, s->length, dir, attrs);
1334 if (sg_dma_address(s) == DMA_MAPPING_ERROR)
1335 goto out_unmap;
1336 sg_dma_len(s) = s->length;
1337 }
1338
1339 return nents;
1340
1341out_unmap:
1342 iommu_dma_unmap_sg_swiotlb(dev, sg, i, dir, attrs | DMA_ATTR_SKIP_CPU_SYNC);
1343 return -EIO;
1344}
1345
1346/*
1347 * The DMA API client is passing in a scatterlist which could describe
1348 * any old buffer layout, but the IOMMU API requires everything to be
1349 * aligned to IOMMU pages. Hence the need for this complicated bit of
1350 * impedance-matching, to be able to hand off a suitably-aligned list,
1351 * but still preserve the original offsets and sizes for the caller.
1352 */
1353int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
1354 enum dma_data_direction dir, unsigned long attrs)
1355{
1356 struct iommu_domain *domain = iommu_get_dma_domain(dev);
1357 struct iommu_dma_cookie *cookie = domain->iova_cookie;
1358 struct iova_domain *iovad = &cookie->iovad;
1359 struct scatterlist *s, *prev = NULL;
1360 int prot = dma_info_to_prot(dir, dev_is_dma_coherent(dev), attrs);
1361 struct pci_p2pdma_map_state p2pdma_state = {};
1362 enum pci_p2pdma_map_type map;
1363 dma_addr_t iova;
1364 size_t iova_len = 0;
1365 unsigned long mask = dma_get_seg_boundary(dev);
1366 ssize_t ret;
1367 int i;
1368
1369 if (static_branch_unlikely(&iommu_deferred_attach_enabled)) {
1370 ret = iommu_deferred_attach(dev, domain);
1371 if (ret)
1372 goto out;
1373 }
1374
1375 if (dev_use_sg_swiotlb(dev, sg, nents, dir))
1376 return iommu_dma_map_sg_swiotlb(dev, sg, nents, dir, attrs);
1377
1378 if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
1379 iommu_dma_sync_sg_for_device(dev, sg, nents, dir);
1380
1381 /*
1382 * Work out how much IOVA space we need, and align the segments to
1383 * IOVA granules for the IOMMU driver to handle. With some clever
1384 * trickery we can modify the list in-place, but reversibly, by
1385 * stashing the unaligned parts in the as-yet-unused DMA fields.
1386 */
1387 for_each_sg(sg, s, nents, i) {
1388 size_t s_iova_off = iova_offset(iovad, s->offset);
1389 size_t s_length = s->length;
1390 size_t pad_len = (mask - iova_len + 1) & mask;
1391
1392 if (is_pci_p2pdma_page(sg_page(s))) {
1393 map = pci_p2pdma_map_segment(&p2pdma_state, dev, s);
1394 switch (map) {
1395 case PCI_P2PDMA_MAP_BUS_ADDR:
1396 /*
1397 * iommu_map_sg() will skip this segment as
1398 * it is marked as a bus address,
1399 * __finalise_sg() will copy the dma address
1400 * into the output segment.
1401 */
1402 continue;
1403 case PCI_P2PDMA_MAP_THRU_HOST_BRIDGE:
1404 /*
1405 * Mapping through host bridge should be
1406 * mapped with regular IOVAs, thus we
1407 * do nothing here and continue below.
1408 */
1409 break;
1410 default:
1411 ret = -EREMOTEIO;
1412 goto out_restore_sg;
1413 }
1414 }
1415
1416 sg_dma_address(s) = s_iova_off;
1417 sg_dma_len(s) = s_length;
1418 s->offset -= s_iova_off;
1419 s_length = iova_align(iovad, s_length + s_iova_off);
1420 s->length = s_length;
1421
1422 /*
1423 * Due to the alignment of our single IOVA allocation, we can
1424 * depend on these assumptions about the segment boundary mask:
1425 * - If mask size >= IOVA size, then the IOVA range cannot
1426 * possibly fall across a boundary, so we don't care.
1427 * - If mask size < IOVA size, then the IOVA range must start
1428 * exactly on a boundary, therefore we can lay things out
1429 * based purely on segment lengths without needing to know
1430 * the actual addresses beforehand.
1431 * - The mask must be a power of 2, so pad_len == 0 if
1432 * iova_len == 0, thus we cannot dereference prev the first
1433 * time through here (i.e. before it has a meaningful value).
1434 */
1435 if (pad_len && pad_len < s_length - 1) {
1436 prev->length += pad_len;
1437 iova_len += pad_len;
1438 }
1439
1440 iova_len += s_length;
1441 prev = s;
1442 }
1443
1444 if (!iova_len)
1445 return __finalise_sg(dev, sg, nents, 0);
1446
1447 iova = iommu_dma_alloc_iova(domain, iova_len, dma_get_mask(dev), dev);
1448 if (!iova) {
1449 ret = -ENOMEM;
1450 goto out_restore_sg;
1451 }
1452
1453 /*
1454 * We'll leave any physical concatenation to the IOMMU driver's
1455 * implementation - it knows better than we do.
1456 */
1457 ret = iommu_map_sg(domain, iova, sg, nents, prot, GFP_ATOMIC);
1458 if (ret < 0 || ret < iova_len)
1459 goto out_free_iova;
1460
1461 return __finalise_sg(dev, sg, nents, iova);
1462
1463out_free_iova:
1464 iommu_dma_free_iova(domain, iova, iova_len, NULL);
1465out_restore_sg:
1466 __invalidate_sg(sg, nents);
1467out:
1468 if (ret != -ENOMEM && ret != -EREMOTEIO)
1469 return -EINVAL;
1470 return ret;
1471}
1472
1473void iommu_dma_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
1474 enum dma_data_direction dir, unsigned long attrs)
1475{
1476 dma_addr_t end = 0, start;
1477 struct scatterlist *tmp;
1478 int i;
1479
1480 if (sg_dma_is_swiotlb(sg)) {
1481 iommu_dma_unmap_sg_swiotlb(dev, sg, nents, dir, attrs);
1482 return;
1483 }
1484
1485 if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
1486 iommu_dma_sync_sg_for_cpu(dev, sg, nents, dir);
1487
1488 /*
1489 * The scatterlist segments are mapped into a single
1490 * contiguous IOVA allocation, the start and end points
1491 * just have to be determined.
1492 */
1493 for_each_sg(sg, tmp, nents, i) {
1494 if (sg_dma_is_bus_address(tmp)) {
1495 sg_dma_unmark_bus_address(tmp);
1496 continue;
1497 }
1498
1499 if (sg_dma_len(tmp) == 0)
1500 break;
1501
1502 start = sg_dma_address(tmp);
1503 break;
1504 }
1505
1506 nents -= i;
1507 for_each_sg(tmp, tmp, nents, i) {
1508 if (sg_dma_is_bus_address(tmp)) {
1509 sg_dma_unmark_bus_address(tmp);
1510 continue;
1511 }
1512
1513 if (sg_dma_len(tmp) == 0)
1514 break;
1515
1516 end = sg_dma_address(tmp) + sg_dma_len(tmp);
1517 }
1518
1519 if (end)
1520 __iommu_dma_unmap(dev, start, end - start);
1521}
1522
1523dma_addr_t iommu_dma_map_resource(struct device *dev, phys_addr_t phys,
1524 size_t size, enum dma_data_direction dir, unsigned long attrs)
1525{
1526 return __iommu_dma_map(dev, phys, size,
1527 dma_info_to_prot(dir, false, attrs) | IOMMU_MMIO,
1528 dma_get_mask(dev));
1529}
1530
1531void iommu_dma_unmap_resource(struct device *dev, dma_addr_t handle,
1532 size_t size, enum dma_data_direction dir, unsigned long attrs)
1533{
1534 __iommu_dma_unmap(dev, handle, size);
1535}
1536
1537static void __iommu_dma_free(struct device *dev, size_t size, void *cpu_addr)
1538{
1539 size_t alloc_size = PAGE_ALIGN(size);
1540 int count = alloc_size >> PAGE_SHIFT;
1541 struct page *page = NULL, **pages = NULL;
1542
1543 /* Non-coherent atomic allocation? Easy */
1544 if (IS_ENABLED(CONFIG_DMA_DIRECT_REMAP) &&
1545 dma_free_from_pool(dev, cpu_addr, alloc_size))
1546 return;
1547
1548 if (is_vmalloc_addr(cpu_addr)) {
1549 /*
1550 * If it the address is remapped, then it's either non-coherent
1551 * or highmem CMA, or an iommu_dma_alloc_remap() construction.
1552 */
1553 pages = dma_common_find_pages(cpu_addr);
1554 if (!pages)
1555 page = vmalloc_to_page(cpu_addr);
1556 dma_common_free_remap(cpu_addr, alloc_size);
1557 } else {
1558 /* Lowmem means a coherent atomic or CMA allocation */
1559 page = virt_to_page(cpu_addr);
1560 }
1561
1562 if (pages)
1563 __iommu_dma_free_pages(pages, count);
1564 if (page)
1565 dma_free_contiguous(dev, page, alloc_size);
1566}
1567
1568void iommu_dma_free(struct device *dev, size_t size, void *cpu_addr,
1569 dma_addr_t handle, unsigned long attrs)
1570{
1571 __iommu_dma_unmap(dev, handle, size);
1572 __iommu_dma_free(dev, size, cpu_addr);
1573}
1574
1575static void *iommu_dma_alloc_pages(struct device *dev, size_t size,
1576 struct page **pagep, gfp_t gfp, unsigned long attrs)
1577{
1578 bool coherent = dev_is_dma_coherent(dev);
1579 size_t alloc_size = PAGE_ALIGN(size);
1580 int node = dev_to_node(dev);
1581 struct page *page = NULL;
1582 void *cpu_addr;
1583
1584 page = dma_alloc_contiguous(dev, alloc_size, gfp);
1585 if (!page)
1586 page = alloc_pages_node(node, gfp, get_order(alloc_size));
1587 if (!page)
1588 return NULL;
1589
1590 if (!coherent || PageHighMem(page)) {
1591 pgprot_t prot = dma_pgprot(dev, PAGE_KERNEL, attrs);
1592
1593 cpu_addr = dma_common_contiguous_remap(page, alloc_size,
1594 prot, __builtin_return_address(0));
1595 if (!cpu_addr)
1596 goto out_free_pages;
1597
1598 if (!coherent)
1599 arch_dma_prep_coherent(page, size);
1600 } else {
1601 cpu_addr = page_address(page);
1602 }
1603
1604 *pagep = page;
1605 memset(cpu_addr, 0, alloc_size);
1606 return cpu_addr;
1607out_free_pages:
1608 dma_free_contiguous(dev, page, alloc_size);
1609 return NULL;
1610}
1611
1612void *iommu_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
1613 gfp_t gfp, unsigned long attrs)
1614{
1615 bool coherent = dev_is_dma_coherent(dev);
1616 int ioprot = dma_info_to_prot(DMA_BIDIRECTIONAL, coherent, attrs);
1617 struct page *page = NULL;
1618 void *cpu_addr;
1619
1620 gfp |= __GFP_ZERO;
1621
1622 if (gfpflags_allow_blocking(gfp) &&
1623 !(attrs & DMA_ATTR_FORCE_CONTIGUOUS)) {
1624 return iommu_dma_alloc_remap(dev, size, handle, gfp, attrs);
1625 }
1626
1627 if (IS_ENABLED(CONFIG_DMA_DIRECT_REMAP) &&
1628 !gfpflags_allow_blocking(gfp) && !coherent)
1629 page = dma_alloc_from_pool(dev, PAGE_ALIGN(size), &cpu_addr,
1630 gfp, NULL);
1631 else
1632 cpu_addr = iommu_dma_alloc_pages(dev, size, &page, gfp, attrs);
1633 if (!cpu_addr)
1634 return NULL;
1635
1636 *handle = __iommu_dma_map(dev, page_to_phys(page), size, ioprot,
1637 dev->coherent_dma_mask);
1638 if (*handle == DMA_MAPPING_ERROR) {
1639 __iommu_dma_free(dev, size, cpu_addr);
1640 return NULL;
1641 }
1642
1643 return cpu_addr;
1644}
1645
1646int iommu_dma_mmap(struct device *dev, struct vm_area_struct *vma,
1647 void *cpu_addr, dma_addr_t dma_addr, size_t size,
1648 unsigned long attrs)
1649{
1650 unsigned long nr_pages = PAGE_ALIGN(size) >> PAGE_SHIFT;
1651 unsigned long pfn, off = vma->vm_pgoff;
1652 int ret;
1653
1654 vma->vm_page_prot = dma_pgprot(dev, vma->vm_page_prot, attrs);
1655
1656 if (dma_mmap_from_dev_coherent(dev, vma, cpu_addr, size, &ret))
1657 return ret;
1658
1659 if (off >= nr_pages || vma_pages(vma) > nr_pages - off)
1660 return -ENXIO;
1661
1662 if (is_vmalloc_addr(cpu_addr)) {
1663 struct page **pages = dma_common_find_pages(cpu_addr);
1664
1665 if (pages)
1666 return vm_map_pages(vma, pages, nr_pages);
1667 pfn = vmalloc_to_pfn(cpu_addr);
1668 } else {
1669 pfn = page_to_pfn(virt_to_page(cpu_addr));
1670 }
1671
1672 return remap_pfn_range(vma, vma->vm_start, pfn + off,
1673 vma->vm_end - vma->vm_start,
1674 vma->vm_page_prot);
1675}
1676
1677int iommu_dma_get_sgtable(struct device *dev, struct sg_table *sgt,
1678 void *cpu_addr, dma_addr_t dma_addr, size_t size,
1679 unsigned long attrs)
1680{
1681 struct page *page;
1682 int ret;
1683
1684 if (is_vmalloc_addr(cpu_addr)) {
1685 struct page **pages = dma_common_find_pages(cpu_addr);
1686
1687 if (pages) {
1688 return sg_alloc_table_from_pages(sgt, pages,
1689 PAGE_ALIGN(size) >> PAGE_SHIFT,
1690 0, size, GFP_KERNEL);
1691 }
1692
1693 page = vmalloc_to_page(cpu_addr);
1694 } else {
1695 page = virt_to_page(cpu_addr);
1696 }
1697
1698 ret = sg_alloc_table(sgt, 1, GFP_KERNEL);
1699 if (!ret)
1700 sg_set_page(sgt->sgl, page, PAGE_ALIGN(size), 0);
1701 return ret;
1702}
1703
1704unsigned long iommu_dma_get_merge_boundary(struct device *dev)
1705{
1706 struct iommu_domain *domain = iommu_get_dma_domain(dev);
1707
1708 return (1UL << __ffs(domain->pgsize_bitmap)) - 1;
1709}
1710
1711size_t iommu_dma_opt_mapping_size(void)
1712{
1713 return iova_rcache_range();
1714}
1715
1716size_t iommu_dma_max_mapping_size(struct device *dev)
1717{
1718 if (dev_is_untrusted(dev))
1719 return swiotlb_max_mapping_size(dev);
1720
1721 return SIZE_MAX;
1722}
1723
1724void iommu_setup_dma_ops(struct device *dev)
1725{
1726 struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
1727
1728 if (dev_is_pci(dev))
1729 dev->iommu->pci_32bit_workaround = !iommu_dma_forcedac;
1730
1731 dev->dma_iommu = iommu_is_dma_domain(domain);
1732 if (dev->dma_iommu && iommu_dma_init_domain(domain, dev))
1733 goto out_err;
1734
1735 return;
1736out_err:
1737 pr_warn("Failed to set up IOMMU for device %s; retaining platform DMA ops\n",
1738 dev_name(dev));
1739 dev->dma_iommu = false;
1740}
1741
1742static bool has_msi_cookie(const struct iommu_domain *domain)
1743{
1744 return domain && (domain->cookie_type == IOMMU_COOKIE_DMA_IOVA ||
1745 domain->cookie_type == IOMMU_COOKIE_DMA_MSI);
1746}
1747
1748static size_t cookie_msi_granule(const struct iommu_domain *domain)
1749{
1750 switch (domain->cookie_type) {
1751 case IOMMU_COOKIE_DMA_IOVA:
1752 return domain->iova_cookie->iovad.granule;
1753 case IOMMU_COOKIE_DMA_MSI:
1754 return PAGE_SIZE;
1755 default:
1756 BUG();
1757 }
1758}
1759
1760static struct list_head *cookie_msi_pages(const struct iommu_domain *domain)
1761{
1762 switch (domain->cookie_type) {
1763 case IOMMU_COOKIE_DMA_IOVA:
1764 return &domain->iova_cookie->msi_page_list;
1765 case IOMMU_COOKIE_DMA_MSI:
1766 return &domain->msi_cookie->msi_page_list;
1767 default:
1768 BUG();
1769 }
1770}
1771
1772static struct iommu_dma_msi_page *iommu_dma_get_msi_page(struct device *dev,
1773 phys_addr_t msi_addr, struct iommu_domain *domain)
1774{
1775 struct list_head *msi_page_list = cookie_msi_pages(domain);
1776 struct iommu_dma_msi_page *msi_page;
1777 dma_addr_t iova;
1778 int prot = IOMMU_WRITE | IOMMU_NOEXEC | IOMMU_MMIO;
1779 size_t size = cookie_msi_granule(domain);
1780
1781 msi_addr &= ~(phys_addr_t)(size - 1);
1782 list_for_each_entry(msi_page, msi_page_list, list)
1783 if (msi_page->phys == msi_addr)
1784 return msi_page;
1785
1786 msi_page = kzalloc(sizeof(*msi_page), GFP_KERNEL);
1787 if (!msi_page)
1788 return NULL;
1789
1790 iova = iommu_dma_alloc_iova(domain, size, dma_get_mask(dev), dev);
1791 if (!iova)
1792 goto out_free_page;
1793
1794 if (iommu_map(domain, iova, msi_addr, size, prot, GFP_KERNEL))
1795 goto out_free_iova;
1796
1797 INIT_LIST_HEAD(&msi_page->list);
1798 msi_page->phys = msi_addr;
1799 msi_page->iova = iova;
1800 list_add(&msi_page->list, msi_page_list);
1801 return msi_page;
1802
1803out_free_iova:
1804 iommu_dma_free_iova(domain, iova, size, NULL);
1805out_free_page:
1806 kfree(msi_page);
1807 return NULL;
1808}
1809
1810int iommu_dma_sw_msi(struct iommu_domain *domain, struct msi_desc *desc,
1811 phys_addr_t msi_addr)
1812{
1813 struct device *dev = msi_desc_to_dev(desc);
1814 const struct iommu_dma_msi_page *msi_page;
1815
1816 if (!has_msi_cookie(domain)) {
1817 msi_desc_set_iommu_msi_iova(desc, 0, 0);
1818 return 0;
1819 }
1820
1821 iommu_group_mutex_assert(dev);
1822 msi_page = iommu_dma_get_msi_page(dev, msi_addr, domain);
1823 if (!msi_page)
1824 return -ENOMEM;
1825
1826 msi_desc_set_iommu_msi_iova(desc, msi_page->iova,
1827 ilog2(cookie_msi_granule(domain)));
1828 return 0;
1829}
1830
1831static int iommu_dma_init(void)
1832{
1833 if (is_kdump_kernel())
1834 static_branch_enable(&iommu_deferred_attach_enabled);
1835
1836 return iova_cache_get();
1837}
1838arch_initcall(iommu_dma_init);