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