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