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