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