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