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