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