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