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