xref: /linux/drivers/iommu/dma-iommu.c (revision 336b4dae6dfecc9aa53a3a68c71b9c1c1d466388)
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/scatterlist.h>
31 #include <linux/spinlock.h>
32 #include <linux/swiotlb.h>
33 #include <linux/vmalloc.h>
34 #include <trace/events/swiotlb.h>
35 
36 #include "dma-iommu.h"
37 #include "iommu-pages.h"
38 
39 struct iommu_dma_msi_page {
40 	struct list_head	list;
41 	dma_addr_t		iova;
42 	phys_addr_t		phys;
43 };
44 
45 enum iommu_dma_cookie_type {
46 	IOMMU_DMA_IOVA_COOKIE,
47 	IOMMU_DMA_MSI_COOKIE,
48 };
49 
50 enum iommu_dma_queue_type {
51 	IOMMU_DMA_OPTS_PER_CPU_QUEUE,
52 	IOMMU_DMA_OPTS_SINGLE_QUEUE,
53 };
54 
55 struct iommu_dma_options {
56 	enum iommu_dma_queue_type qt;
57 	size_t		fq_size;
58 	unsigned int	fq_timeout;
59 };
60 
61 struct iommu_dma_cookie {
62 	enum iommu_dma_cookie_type	type;
63 	union {
64 		/* Full allocator for IOMMU_DMA_IOVA_COOKIE */
65 		struct {
66 			struct iova_domain	iovad;
67 			/* Flush queue */
68 			union {
69 				struct iova_fq	*single_fq;
70 				struct iova_fq	__percpu *percpu_fq;
71 			};
72 			/* Number of TLB flushes that have been started */
73 			atomic64_t		fq_flush_start_cnt;
74 			/* Number of TLB flushes that have been finished */
75 			atomic64_t		fq_flush_finish_cnt;
76 			/* Timer to regularily empty the flush queues */
77 			struct timer_list	fq_timer;
78 			/* 1 when timer is active, 0 when not */
79 			atomic_t		fq_timer_on;
80 		};
81 		/* Trivial linear page allocator for IOMMU_DMA_MSI_COOKIE */
82 		dma_addr_t		msi_iova;
83 	};
84 	struct list_head		msi_page_list;
85 
86 	/* Domain for flush queue callback; NULL if flush queue not in use */
87 	struct iommu_domain		*fq_domain;
88 	/* Options for dma-iommu use */
89 	struct iommu_dma_options	options;
90 };
91 
92 static DEFINE_STATIC_KEY_FALSE(iommu_deferred_attach_enabled);
93 bool iommu_dma_forcedac __read_mostly;
94 
iommu_dma_forcedac_setup(char * str)95 static int __init iommu_dma_forcedac_setup(char *str)
96 {
97 	int ret = kstrtobool(str, &iommu_dma_forcedac);
98 
99 	if (!ret && iommu_dma_forcedac)
100 		pr_info("Forcing DAC for PCI devices\n");
101 	return ret;
102 }
103 early_param("iommu.forcedac", iommu_dma_forcedac_setup);
104 
105 static int iommu_dma_sw_msi(struct iommu_domain *domain, struct msi_desc *desc,
106 			    phys_addr_t msi_addr);
107 
108 /* Number of entries per flush queue */
109 #define IOVA_DEFAULT_FQ_SIZE	256
110 #define IOVA_SINGLE_FQ_SIZE	32768
111 
112 /* Timeout (in ms) after which entries are flushed from the queue */
113 #define IOVA_DEFAULT_FQ_TIMEOUT	10
114 #define IOVA_SINGLE_FQ_TIMEOUT	1000
115 
116 /* Flush queue entry for deferred flushing */
117 struct iova_fq_entry {
118 	unsigned long iova_pfn;
119 	unsigned long pages;
120 	struct list_head freelist;
121 	u64 counter; /* Flush counter when this entry was added */
122 };
123 
124 /* Per-CPU flush queue structure */
125 struct iova_fq {
126 	spinlock_t lock;
127 	unsigned int head, tail;
128 	unsigned int mod_mask;
129 	struct iova_fq_entry entries[];
130 };
131 
132 #define fq_ring_for_each(i, fq) \
133 	for ((i) = (fq)->head; (i) != (fq)->tail; (i) = ((i) + 1) & (fq)->mod_mask)
134 
fq_full(struct iova_fq * fq)135 static inline bool fq_full(struct iova_fq *fq)
136 {
137 	assert_spin_locked(&fq->lock);
138 	return (((fq->tail + 1) & fq->mod_mask) == fq->head);
139 }
140 
fq_ring_add(struct iova_fq * fq)141 static inline unsigned int fq_ring_add(struct iova_fq *fq)
142 {
143 	unsigned int idx = fq->tail;
144 
145 	assert_spin_locked(&fq->lock);
146 
147 	fq->tail = (idx + 1) & fq->mod_mask;
148 
149 	return idx;
150 }
151 
fq_ring_free_locked(struct iommu_dma_cookie * cookie,struct iova_fq * fq)152 static void fq_ring_free_locked(struct iommu_dma_cookie *cookie, struct iova_fq *fq)
153 {
154 	u64 counter = atomic64_read(&cookie->fq_flush_finish_cnt);
155 	unsigned int idx;
156 
157 	assert_spin_locked(&fq->lock);
158 
159 	fq_ring_for_each(idx, fq) {
160 
161 		if (fq->entries[idx].counter >= counter)
162 			break;
163 
164 		iommu_put_pages_list(&fq->entries[idx].freelist);
165 		free_iova_fast(&cookie->iovad,
166 			       fq->entries[idx].iova_pfn,
167 			       fq->entries[idx].pages);
168 
169 		fq->head = (fq->head + 1) & fq->mod_mask;
170 	}
171 }
172 
fq_ring_free(struct iommu_dma_cookie * cookie,struct iova_fq * fq)173 static void fq_ring_free(struct iommu_dma_cookie *cookie, struct iova_fq *fq)
174 {
175 	unsigned long flags;
176 
177 	spin_lock_irqsave(&fq->lock, flags);
178 	fq_ring_free_locked(cookie, fq);
179 	spin_unlock_irqrestore(&fq->lock, flags);
180 }
181 
fq_flush_iotlb(struct iommu_dma_cookie * cookie)182 static void fq_flush_iotlb(struct iommu_dma_cookie *cookie)
183 {
184 	atomic64_inc(&cookie->fq_flush_start_cnt);
185 	cookie->fq_domain->ops->flush_iotlb_all(cookie->fq_domain);
186 	atomic64_inc(&cookie->fq_flush_finish_cnt);
187 }
188 
fq_flush_timeout(struct timer_list * t)189 static void fq_flush_timeout(struct timer_list *t)
190 {
191 	struct iommu_dma_cookie *cookie = from_timer(cookie, t, fq_timer);
192 	int cpu;
193 
194 	atomic_set(&cookie->fq_timer_on, 0);
195 	fq_flush_iotlb(cookie);
196 
197 	if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE) {
198 		fq_ring_free(cookie, cookie->single_fq);
199 	} else {
200 		for_each_possible_cpu(cpu)
201 			fq_ring_free(cookie, per_cpu_ptr(cookie->percpu_fq, cpu));
202 	}
203 }
204 
queue_iova(struct iommu_dma_cookie * cookie,unsigned long pfn,unsigned long pages,struct list_head * freelist)205 static void queue_iova(struct iommu_dma_cookie *cookie,
206 		unsigned long pfn, unsigned long pages,
207 		struct list_head *freelist)
208 {
209 	struct iova_fq *fq;
210 	unsigned long flags;
211 	unsigned int idx;
212 
213 	/*
214 	 * Order against the IOMMU driver's pagetable update from unmapping
215 	 * @pte, to guarantee that fq_flush_iotlb() observes that if called
216 	 * from a different CPU before we release the lock below. Full barrier
217 	 * so it also pairs with iommu_dma_init_fq() to avoid seeing partially
218 	 * written fq state here.
219 	 */
220 	smp_mb();
221 
222 	if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE)
223 		fq = cookie->single_fq;
224 	else
225 		fq = raw_cpu_ptr(cookie->percpu_fq);
226 
227 	spin_lock_irqsave(&fq->lock, flags);
228 
229 	/*
230 	 * First remove all entries from the flush queue that have already been
231 	 * flushed out on another CPU. This makes the fq_full() check below less
232 	 * likely to be true.
233 	 */
234 	fq_ring_free_locked(cookie, fq);
235 
236 	if (fq_full(fq)) {
237 		fq_flush_iotlb(cookie);
238 		fq_ring_free_locked(cookie, fq);
239 	}
240 
241 	idx = fq_ring_add(fq);
242 
243 	fq->entries[idx].iova_pfn = pfn;
244 	fq->entries[idx].pages    = pages;
245 	fq->entries[idx].counter  = atomic64_read(&cookie->fq_flush_start_cnt);
246 	list_splice(freelist, &fq->entries[idx].freelist);
247 
248 	spin_unlock_irqrestore(&fq->lock, flags);
249 
250 	/* Avoid false sharing as much as possible. */
251 	if (!atomic_read(&cookie->fq_timer_on) &&
252 	    !atomic_xchg(&cookie->fq_timer_on, 1))
253 		mod_timer(&cookie->fq_timer,
254 			  jiffies + msecs_to_jiffies(cookie->options.fq_timeout));
255 }
256 
iommu_dma_free_fq_single(struct iova_fq * fq)257 static void iommu_dma_free_fq_single(struct iova_fq *fq)
258 {
259 	int idx;
260 
261 	fq_ring_for_each(idx, fq)
262 		iommu_put_pages_list(&fq->entries[idx].freelist);
263 	vfree(fq);
264 }
265 
iommu_dma_free_fq_percpu(struct iova_fq __percpu * percpu_fq)266 static void iommu_dma_free_fq_percpu(struct iova_fq __percpu *percpu_fq)
267 {
268 	int cpu, idx;
269 
270 	/* The IOVAs will be torn down separately, so just free our queued pages */
271 	for_each_possible_cpu(cpu) {
272 		struct iova_fq *fq = per_cpu_ptr(percpu_fq, cpu);
273 
274 		fq_ring_for_each(idx, fq)
275 			iommu_put_pages_list(&fq->entries[idx].freelist);
276 	}
277 
278 	free_percpu(percpu_fq);
279 }
280 
iommu_dma_free_fq(struct iommu_dma_cookie * cookie)281 static void iommu_dma_free_fq(struct iommu_dma_cookie *cookie)
282 {
283 	if (!cookie->fq_domain)
284 		return;
285 
286 	del_timer_sync(&cookie->fq_timer);
287 	if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE)
288 		iommu_dma_free_fq_single(cookie->single_fq);
289 	else
290 		iommu_dma_free_fq_percpu(cookie->percpu_fq);
291 }
292 
iommu_dma_init_one_fq(struct iova_fq * fq,size_t fq_size)293 static void iommu_dma_init_one_fq(struct iova_fq *fq, size_t fq_size)
294 {
295 	int i;
296 
297 	fq->head = 0;
298 	fq->tail = 0;
299 	fq->mod_mask = fq_size - 1;
300 
301 	spin_lock_init(&fq->lock);
302 
303 	for (i = 0; i < fq_size; i++)
304 		INIT_LIST_HEAD(&fq->entries[i].freelist);
305 }
306 
iommu_dma_init_fq_single(struct iommu_dma_cookie * cookie)307 static int iommu_dma_init_fq_single(struct iommu_dma_cookie *cookie)
308 {
309 	size_t fq_size = cookie->options.fq_size;
310 	struct iova_fq *queue;
311 
312 	queue = vmalloc(struct_size(queue, entries, fq_size));
313 	if (!queue)
314 		return -ENOMEM;
315 	iommu_dma_init_one_fq(queue, fq_size);
316 	cookie->single_fq = queue;
317 
318 	return 0;
319 }
320 
iommu_dma_init_fq_percpu(struct iommu_dma_cookie * cookie)321 static int iommu_dma_init_fq_percpu(struct iommu_dma_cookie *cookie)
322 {
323 	size_t fq_size = cookie->options.fq_size;
324 	struct iova_fq __percpu *queue;
325 	int cpu;
326 
327 	queue = __alloc_percpu(struct_size(queue, entries, fq_size),
328 			       __alignof__(*queue));
329 	if (!queue)
330 		return -ENOMEM;
331 
332 	for_each_possible_cpu(cpu)
333 		iommu_dma_init_one_fq(per_cpu_ptr(queue, cpu), fq_size);
334 	cookie->percpu_fq = queue;
335 	return 0;
336 }
337 
338 /* sysfs updates are serialised by the mutex of the group owning @domain */
iommu_dma_init_fq(struct iommu_domain * domain)339 int iommu_dma_init_fq(struct iommu_domain *domain)
340 {
341 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
342 	int rc;
343 
344 	if (cookie->fq_domain)
345 		return 0;
346 
347 	atomic64_set(&cookie->fq_flush_start_cnt,  0);
348 	atomic64_set(&cookie->fq_flush_finish_cnt, 0);
349 
350 	if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE)
351 		rc = iommu_dma_init_fq_single(cookie);
352 	else
353 		rc = iommu_dma_init_fq_percpu(cookie);
354 
355 	if (rc) {
356 		pr_warn("iova flush queue initialization failed\n");
357 		return -ENOMEM;
358 	}
359 
360 	timer_setup(&cookie->fq_timer, fq_flush_timeout, 0);
361 	atomic_set(&cookie->fq_timer_on, 0);
362 	/*
363 	 * Prevent incomplete fq state being observable. Pairs with path from
364 	 * __iommu_dma_unmap() through iommu_dma_free_iova() to queue_iova()
365 	 */
366 	smp_wmb();
367 	WRITE_ONCE(cookie->fq_domain, domain);
368 	return 0;
369 }
370 
cookie_msi_granule(struct iommu_dma_cookie * cookie)371 static inline size_t cookie_msi_granule(struct iommu_dma_cookie *cookie)
372 {
373 	if (cookie->type == IOMMU_DMA_IOVA_COOKIE)
374 		return cookie->iovad.granule;
375 	return PAGE_SIZE;
376 }
377 
cookie_alloc(enum iommu_dma_cookie_type type)378 static struct iommu_dma_cookie *cookie_alloc(enum iommu_dma_cookie_type type)
379 {
380 	struct iommu_dma_cookie *cookie;
381 
382 	cookie = kzalloc(sizeof(*cookie), GFP_KERNEL);
383 	if (cookie) {
384 		INIT_LIST_HEAD(&cookie->msi_page_list);
385 		cookie->type = type;
386 	}
387 	return cookie;
388 }
389 
390 /**
391  * iommu_get_dma_cookie - Acquire DMA-API resources for a domain
392  * @domain: IOMMU domain to prepare for DMA-API usage
393  */
iommu_get_dma_cookie(struct iommu_domain * domain)394 int iommu_get_dma_cookie(struct iommu_domain *domain)
395 {
396 	if (domain->iova_cookie)
397 		return -EEXIST;
398 
399 	domain->iova_cookie = cookie_alloc(IOMMU_DMA_IOVA_COOKIE);
400 	if (!domain->iova_cookie)
401 		return -ENOMEM;
402 
403 	iommu_domain_set_sw_msi(domain, iommu_dma_sw_msi);
404 	return 0;
405 }
406 
407 /**
408  * iommu_get_msi_cookie - Acquire just MSI remapping resources
409  * @domain: IOMMU domain to prepare
410  * @base: Start address of IOVA region for MSI mappings
411  *
412  * Users who manage their own IOVA allocation and do not want DMA API support,
413  * but would still like to take advantage of automatic MSI remapping, can use
414  * this to initialise their own domain appropriately. Users should reserve a
415  * contiguous IOVA region, starting at @base, large enough to accommodate the
416  * number of PAGE_SIZE mappings necessary to cover every MSI doorbell address
417  * used by the devices attached to @domain.
418  */
iommu_get_msi_cookie(struct iommu_domain * domain,dma_addr_t base)419 int iommu_get_msi_cookie(struct iommu_domain *domain, dma_addr_t base)
420 {
421 	struct iommu_dma_cookie *cookie;
422 
423 	if (domain->type != IOMMU_DOMAIN_UNMANAGED)
424 		return -EINVAL;
425 
426 	if (domain->iova_cookie)
427 		return -EEXIST;
428 
429 	cookie = cookie_alloc(IOMMU_DMA_MSI_COOKIE);
430 	if (!cookie)
431 		return -ENOMEM;
432 
433 	cookie->msi_iova = base;
434 	domain->iova_cookie = cookie;
435 	iommu_domain_set_sw_msi(domain, iommu_dma_sw_msi);
436 	return 0;
437 }
438 EXPORT_SYMBOL(iommu_get_msi_cookie);
439 
440 /**
441  * iommu_put_dma_cookie - Release a domain's DMA mapping resources
442  * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie() or
443  *          iommu_get_msi_cookie()
444  */
iommu_put_dma_cookie(struct iommu_domain * domain)445 void iommu_put_dma_cookie(struct iommu_domain *domain)
446 {
447 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
448 	struct iommu_dma_msi_page *msi, *tmp;
449 
450 #if IS_ENABLED(CONFIG_IRQ_MSI_IOMMU)
451 	if (domain->sw_msi != iommu_dma_sw_msi)
452 		return;
453 #endif
454 
455 	if (!cookie)
456 		return;
457 
458 	if (cookie->type == IOMMU_DMA_IOVA_COOKIE && cookie->iovad.granule) {
459 		iommu_dma_free_fq(cookie);
460 		put_iova_domain(&cookie->iovad);
461 	}
462 
463 	list_for_each_entry_safe(msi, tmp, &cookie->msi_page_list, list) {
464 		list_del(&msi->list);
465 		kfree(msi);
466 	}
467 	kfree(cookie);
468 	domain->iova_cookie = NULL;
469 }
470 
471 /**
472  * iommu_dma_get_resv_regions - Reserved region driver helper
473  * @dev: Device from iommu_get_resv_regions()
474  * @list: Reserved region list from iommu_get_resv_regions()
475  *
476  * IOMMU drivers can use this to implement their .get_resv_regions callback
477  * for general non-IOMMU-specific reservations. Currently, this covers GICv3
478  * ITS region reservation on ACPI based ARM platforms that may require HW MSI
479  * reservation.
480  */
iommu_dma_get_resv_regions(struct device * dev,struct list_head * list)481 void iommu_dma_get_resv_regions(struct device *dev, struct list_head *list)
482 {
483 
484 	if (!is_of_node(dev_iommu_fwspec_get(dev)->iommu_fwnode))
485 		iort_iommu_get_resv_regions(dev, list);
486 
487 	if (dev->of_node)
488 		of_iommu_get_resv_regions(dev, list);
489 }
490 EXPORT_SYMBOL(iommu_dma_get_resv_regions);
491 
cookie_init_hw_msi_region(struct iommu_dma_cookie * cookie,phys_addr_t start,phys_addr_t end)492 static int cookie_init_hw_msi_region(struct iommu_dma_cookie *cookie,
493 		phys_addr_t start, phys_addr_t end)
494 {
495 	struct iova_domain *iovad = &cookie->iovad;
496 	struct iommu_dma_msi_page *msi_page;
497 	int i, num_pages;
498 
499 	start -= iova_offset(iovad, start);
500 	num_pages = iova_align(iovad, end - start) >> iova_shift(iovad);
501 
502 	for (i = 0; i < num_pages; i++) {
503 		msi_page = kmalloc(sizeof(*msi_page), GFP_KERNEL);
504 		if (!msi_page)
505 			return -ENOMEM;
506 
507 		msi_page->phys = start;
508 		msi_page->iova = start;
509 		INIT_LIST_HEAD(&msi_page->list);
510 		list_add(&msi_page->list, &cookie->msi_page_list);
511 		start += iovad->granule;
512 	}
513 
514 	return 0;
515 }
516 
iommu_dma_ranges_sort(void * priv,const struct list_head * a,const struct list_head * b)517 static int iommu_dma_ranges_sort(void *priv, const struct list_head *a,
518 		const struct list_head *b)
519 {
520 	struct resource_entry *res_a = list_entry(a, typeof(*res_a), node);
521 	struct resource_entry *res_b = list_entry(b, typeof(*res_b), node);
522 
523 	return res_a->res->start > res_b->res->start;
524 }
525 
iova_reserve_pci_windows(struct pci_dev * dev,struct iova_domain * iovad)526 static int iova_reserve_pci_windows(struct pci_dev *dev,
527 		struct iova_domain *iovad)
528 {
529 	struct pci_host_bridge *bridge = pci_find_host_bridge(dev->bus);
530 	struct resource_entry *window;
531 	unsigned long lo, hi;
532 	phys_addr_t start = 0, end;
533 
534 	resource_list_for_each_entry(window, &bridge->windows) {
535 		if (resource_type(window->res) != IORESOURCE_MEM)
536 			continue;
537 
538 		lo = iova_pfn(iovad, window->res->start - window->offset);
539 		hi = iova_pfn(iovad, window->res->end - window->offset);
540 		reserve_iova(iovad, lo, hi);
541 	}
542 
543 	/* Get reserved DMA windows from host bridge */
544 	list_sort(NULL, &bridge->dma_ranges, iommu_dma_ranges_sort);
545 	resource_list_for_each_entry(window, &bridge->dma_ranges) {
546 		end = window->res->start - window->offset;
547 resv_iova:
548 		if (end > start) {
549 			lo = iova_pfn(iovad, start);
550 			hi = iova_pfn(iovad, end);
551 			reserve_iova(iovad, lo, hi);
552 		} else if (end < start) {
553 			/* DMA ranges should be non-overlapping */
554 			dev_err(&dev->dev,
555 				"Failed to reserve IOVA [%pa-%pa]\n",
556 				&start, &end);
557 			return -EINVAL;
558 		}
559 
560 		start = window->res->end - window->offset + 1;
561 		/* If window is last entry */
562 		if (window->node.next == &bridge->dma_ranges &&
563 		    end != ~(phys_addr_t)0) {
564 			end = ~(phys_addr_t)0;
565 			goto resv_iova;
566 		}
567 	}
568 
569 	return 0;
570 }
571 
iova_reserve_iommu_regions(struct device * dev,struct iommu_domain * domain)572 static int iova_reserve_iommu_regions(struct device *dev,
573 		struct iommu_domain *domain)
574 {
575 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
576 	struct iova_domain *iovad = &cookie->iovad;
577 	struct iommu_resv_region *region;
578 	LIST_HEAD(resv_regions);
579 	int ret = 0;
580 
581 	if (dev_is_pci(dev)) {
582 		ret = iova_reserve_pci_windows(to_pci_dev(dev), iovad);
583 		if (ret)
584 			return ret;
585 	}
586 
587 	iommu_get_resv_regions(dev, &resv_regions);
588 	list_for_each_entry(region, &resv_regions, list) {
589 		unsigned long lo, hi;
590 
591 		/* We ARE the software that manages these! */
592 		if (region->type == IOMMU_RESV_SW_MSI)
593 			continue;
594 
595 		lo = iova_pfn(iovad, region->start);
596 		hi = iova_pfn(iovad, region->start + region->length - 1);
597 		reserve_iova(iovad, lo, hi);
598 
599 		if (region->type == IOMMU_RESV_MSI)
600 			ret = cookie_init_hw_msi_region(cookie, region->start,
601 					region->start + region->length);
602 		if (ret)
603 			break;
604 	}
605 	iommu_put_resv_regions(dev, &resv_regions);
606 
607 	return ret;
608 }
609 
dev_is_untrusted(struct device * dev)610 static bool dev_is_untrusted(struct device *dev)
611 {
612 	return dev_is_pci(dev) && to_pci_dev(dev)->untrusted;
613 }
614 
dev_use_swiotlb(struct device * dev,size_t size,enum dma_data_direction dir)615 static bool dev_use_swiotlb(struct device *dev, size_t size,
616 			    enum dma_data_direction dir)
617 {
618 	return IS_ENABLED(CONFIG_SWIOTLB) &&
619 		(dev_is_untrusted(dev) ||
620 		 dma_kmalloc_needs_bounce(dev, size, dir));
621 }
622 
dev_use_sg_swiotlb(struct device * dev,struct scatterlist * sg,int nents,enum dma_data_direction dir)623 static bool dev_use_sg_swiotlb(struct device *dev, struct scatterlist *sg,
624 			       int nents, enum dma_data_direction dir)
625 {
626 	struct scatterlist *s;
627 	int i;
628 
629 	if (!IS_ENABLED(CONFIG_SWIOTLB))
630 		return false;
631 
632 	if (dev_is_untrusted(dev))
633 		return true;
634 
635 	/*
636 	 * If kmalloc() buffers are not DMA-safe for this device and
637 	 * direction, check the individual lengths in the sg list. If any
638 	 * element is deemed unsafe, use the swiotlb for bouncing.
639 	 */
640 	if (!dma_kmalloc_safe(dev, dir)) {
641 		for_each_sg(sg, s, nents, i)
642 			if (!dma_kmalloc_size_aligned(s->length))
643 				return true;
644 	}
645 
646 	return false;
647 }
648 
649 /**
650  * iommu_dma_init_options - Initialize dma-iommu options
651  * @options: The options to be initialized
652  * @dev: Device the options are set for
653  *
654  * This allows tuning dma-iommu specific to device properties
655  */
iommu_dma_init_options(struct iommu_dma_options * options,struct device * dev)656 static void iommu_dma_init_options(struct iommu_dma_options *options,
657 				   struct device *dev)
658 {
659 	/* Shadowing IOTLB flushes do better with a single large queue */
660 	if (dev->iommu->shadow_on_flush) {
661 		options->qt = IOMMU_DMA_OPTS_SINGLE_QUEUE;
662 		options->fq_timeout = IOVA_SINGLE_FQ_TIMEOUT;
663 		options->fq_size = IOVA_SINGLE_FQ_SIZE;
664 	} else {
665 		options->qt = IOMMU_DMA_OPTS_PER_CPU_QUEUE;
666 		options->fq_size = IOVA_DEFAULT_FQ_SIZE;
667 		options->fq_timeout = IOVA_DEFAULT_FQ_TIMEOUT;
668 	}
669 }
670 
671 /**
672  * iommu_dma_init_domain - Initialise a DMA mapping domain
673  * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie()
674  * @dev: Device the domain is being initialised for
675  *
676  * If the geometry and dma_range_map include address 0, we reserve that page
677  * to ensure it is an invalid IOVA. It is safe to reinitialise a domain, but
678  * any change which could make prior IOVAs invalid will fail.
679  */
iommu_dma_init_domain(struct iommu_domain * domain,struct device * dev)680 static int iommu_dma_init_domain(struct iommu_domain *domain, struct device *dev)
681 {
682 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
683 	const struct bus_dma_region *map = dev->dma_range_map;
684 	unsigned long order, base_pfn;
685 	struct iova_domain *iovad;
686 	int ret;
687 
688 	if (!cookie || cookie->type != IOMMU_DMA_IOVA_COOKIE)
689 		return -EINVAL;
690 
691 	iovad = &cookie->iovad;
692 
693 	/* Use the smallest supported page size for IOVA granularity */
694 	order = __ffs(domain->pgsize_bitmap);
695 	base_pfn = 1;
696 
697 	/* Check the domain allows at least some access to the device... */
698 	if (map) {
699 		if (dma_range_map_min(map) > domain->geometry.aperture_end ||
700 		    dma_range_map_max(map) < domain->geometry.aperture_start) {
701 			pr_warn("specified DMA range outside IOMMU capability\n");
702 			return -EFAULT;
703 		}
704 	}
705 	/* ...then finally give it a kicking to make sure it fits */
706 	base_pfn = max_t(unsigned long, base_pfn,
707 			 domain->geometry.aperture_start >> order);
708 
709 	/* start_pfn is always nonzero for an already-initialised domain */
710 	if (iovad->start_pfn) {
711 		if (1UL << order != iovad->granule ||
712 		    base_pfn != iovad->start_pfn) {
713 			pr_warn("Incompatible range for DMA domain\n");
714 			return -EFAULT;
715 		}
716 
717 		return 0;
718 	}
719 
720 	init_iova_domain(iovad, 1UL << order, base_pfn);
721 	ret = iova_domain_init_rcaches(iovad);
722 	if (ret)
723 		return ret;
724 
725 	iommu_dma_init_options(&cookie->options, dev);
726 
727 	/* If the FQ fails we can simply fall back to strict mode */
728 	if (domain->type == IOMMU_DOMAIN_DMA_FQ &&
729 	    (!device_iommu_capable(dev, IOMMU_CAP_DEFERRED_FLUSH) || iommu_dma_init_fq(domain)))
730 		domain->type = IOMMU_DOMAIN_DMA;
731 
732 	return iova_reserve_iommu_regions(dev, domain);
733 }
734 
735 /**
736  * dma_info_to_prot - Translate DMA API directions and attributes to IOMMU API
737  *                    page flags.
738  * @dir: Direction of DMA transfer
739  * @coherent: Is the DMA master cache-coherent?
740  * @attrs: DMA attributes for the mapping
741  *
742  * Return: corresponding IOMMU API page protection flags
743  */
dma_info_to_prot(enum dma_data_direction dir,bool coherent,unsigned long attrs)744 static int dma_info_to_prot(enum dma_data_direction dir, bool coherent,
745 		     unsigned long attrs)
746 {
747 	int prot = coherent ? IOMMU_CACHE : 0;
748 
749 	if (attrs & DMA_ATTR_PRIVILEGED)
750 		prot |= IOMMU_PRIV;
751 
752 	switch (dir) {
753 	case DMA_BIDIRECTIONAL:
754 		return prot | IOMMU_READ | IOMMU_WRITE;
755 	case DMA_TO_DEVICE:
756 		return prot | IOMMU_READ;
757 	case DMA_FROM_DEVICE:
758 		return prot | IOMMU_WRITE;
759 	default:
760 		return 0;
761 	}
762 }
763 
iommu_dma_alloc_iova(struct iommu_domain * domain,size_t size,u64 dma_limit,struct device * dev)764 static dma_addr_t iommu_dma_alloc_iova(struct iommu_domain *domain,
765 		size_t size, u64 dma_limit, struct device *dev)
766 {
767 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
768 	struct iova_domain *iovad = &cookie->iovad;
769 	unsigned long shift, iova_len, iova;
770 
771 	if (cookie->type == IOMMU_DMA_MSI_COOKIE) {
772 		cookie->msi_iova += size;
773 		return cookie->msi_iova - size;
774 	}
775 
776 	shift = iova_shift(iovad);
777 	iova_len = size >> shift;
778 
779 	dma_limit = min_not_zero(dma_limit, dev->bus_dma_limit);
780 
781 	if (domain->geometry.force_aperture)
782 		dma_limit = min(dma_limit, (u64)domain->geometry.aperture_end);
783 
784 	/*
785 	 * Try to use all the 32-bit PCI addresses first. The original SAC vs.
786 	 * DAC reasoning loses relevance with PCIe, but enough hardware and
787 	 * firmware bugs are still lurking out there that it's safest not to
788 	 * venture into the 64-bit space until necessary.
789 	 *
790 	 * If your device goes wrong after seeing the notice then likely either
791 	 * its driver is not setting DMA masks accurately, the hardware has
792 	 * some inherent bug in handling >32-bit addresses, or not all the
793 	 * expected address bits are wired up between the device and the IOMMU.
794 	 */
795 	if (dma_limit > DMA_BIT_MASK(32) && dev->iommu->pci_32bit_workaround) {
796 		iova = alloc_iova_fast(iovad, iova_len,
797 				       DMA_BIT_MASK(32) >> shift, false);
798 		if (iova)
799 			goto done;
800 
801 		dev->iommu->pci_32bit_workaround = false;
802 		dev_notice(dev, "Using %d-bit DMA addresses\n", bits_per(dma_limit));
803 	}
804 
805 	iova = alloc_iova_fast(iovad, iova_len, dma_limit >> shift, true);
806 done:
807 	return (dma_addr_t)iova << shift;
808 }
809 
iommu_dma_free_iova(struct iommu_dma_cookie * cookie,dma_addr_t iova,size_t size,struct iommu_iotlb_gather * gather)810 static void iommu_dma_free_iova(struct iommu_dma_cookie *cookie,
811 		dma_addr_t iova, size_t size, struct iommu_iotlb_gather *gather)
812 {
813 	struct iova_domain *iovad = &cookie->iovad;
814 
815 	/* The MSI case is only ever cleaning up its most recent allocation */
816 	if (cookie->type == IOMMU_DMA_MSI_COOKIE)
817 		cookie->msi_iova -= size;
818 	else if (gather && gather->queued)
819 		queue_iova(cookie, iova_pfn(iovad, iova),
820 				size >> iova_shift(iovad),
821 				&gather->freelist);
822 	else
823 		free_iova_fast(iovad, iova_pfn(iovad, iova),
824 				size >> iova_shift(iovad));
825 }
826 
__iommu_dma_unmap(struct device * dev,dma_addr_t dma_addr,size_t size)827 static void __iommu_dma_unmap(struct device *dev, dma_addr_t dma_addr,
828 		size_t size)
829 {
830 	struct iommu_domain *domain = iommu_get_dma_domain(dev);
831 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
832 	struct iova_domain *iovad = &cookie->iovad;
833 	size_t iova_off = iova_offset(iovad, dma_addr);
834 	struct iommu_iotlb_gather iotlb_gather;
835 	size_t unmapped;
836 
837 	dma_addr -= iova_off;
838 	size = iova_align(iovad, size + iova_off);
839 	iommu_iotlb_gather_init(&iotlb_gather);
840 	iotlb_gather.queued = READ_ONCE(cookie->fq_domain);
841 
842 	unmapped = iommu_unmap_fast(domain, dma_addr, size, &iotlb_gather);
843 	WARN_ON(unmapped != size);
844 
845 	if (!iotlb_gather.queued)
846 		iommu_iotlb_sync(domain, &iotlb_gather);
847 	iommu_dma_free_iova(cookie, dma_addr, size, &iotlb_gather);
848 }
849 
__iommu_dma_map(struct device * dev,phys_addr_t phys,size_t size,int prot,u64 dma_mask)850 static dma_addr_t __iommu_dma_map(struct device *dev, phys_addr_t phys,
851 		size_t size, int prot, u64 dma_mask)
852 {
853 	struct iommu_domain *domain = iommu_get_dma_domain(dev);
854 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
855 	struct iova_domain *iovad = &cookie->iovad;
856 	size_t iova_off = iova_offset(iovad, phys);
857 	dma_addr_t iova;
858 
859 	if (static_branch_unlikely(&iommu_deferred_attach_enabled) &&
860 	    iommu_deferred_attach(dev, domain))
861 		return DMA_MAPPING_ERROR;
862 
863 	/* If anyone ever wants this we'd need support in the IOVA allocator */
864 	if (dev_WARN_ONCE(dev, dma_get_min_align_mask(dev) > iova_mask(iovad),
865 	    "Unsupported alignment constraint\n"))
866 		return DMA_MAPPING_ERROR;
867 
868 	size = iova_align(iovad, size + iova_off);
869 
870 	iova = iommu_dma_alloc_iova(domain, size, dma_mask, dev);
871 	if (!iova)
872 		return DMA_MAPPING_ERROR;
873 
874 	if (iommu_map(domain, iova, phys - iova_off, size, prot, GFP_ATOMIC)) {
875 		iommu_dma_free_iova(cookie, iova, size, NULL);
876 		return DMA_MAPPING_ERROR;
877 	}
878 	return iova + iova_off;
879 }
880 
__iommu_dma_free_pages(struct page ** pages,int count)881 static void __iommu_dma_free_pages(struct page **pages, int count)
882 {
883 	while (count--)
884 		__free_page(pages[count]);
885 	kvfree(pages);
886 }
887 
__iommu_dma_alloc_pages(struct device * dev,unsigned int count,unsigned long order_mask,gfp_t gfp)888 static struct page **__iommu_dma_alloc_pages(struct device *dev,
889 		unsigned int count, unsigned long order_mask, gfp_t gfp)
890 {
891 	struct page **pages;
892 	unsigned int i = 0, nid = dev_to_node(dev);
893 
894 	order_mask &= GENMASK(MAX_PAGE_ORDER, 0);
895 	if (!order_mask)
896 		return NULL;
897 
898 	pages = kvcalloc(count, sizeof(*pages), GFP_KERNEL);
899 	if (!pages)
900 		return NULL;
901 
902 	/* IOMMU can map any pages, so himem can also be used here */
903 	gfp |= __GFP_NOWARN | __GFP_HIGHMEM;
904 
905 	while (count) {
906 		struct page *page = NULL;
907 		unsigned int order_size;
908 
909 		/*
910 		 * Higher-order allocations are a convenience rather
911 		 * than a necessity, hence using __GFP_NORETRY until
912 		 * falling back to minimum-order allocations.
913 		 */
914 		for (order_mask &= GENMASK(__fls(count), 0);
915 		     order_mask; order_mask &= ~order_size) {
916 			unsigned int order = __fls(order_mask);
917 			gfp_t alloc_flags = gfp;
918 
919 			order_size = 1U << order;
920 			if (order_mask > order_size)
921 				alloc_flags |= __GFP_NORETRY;
922 			page = alloc_pages_node(nid, alloc_flags, order);
923 			if (!page)
924 				continue;
925 			if (order)
926 				split_page(page, order);
927 			break;
928 		}
929 		if (!page) {
930 			__iommu_dma_free_pages(pages, i);
931 			return NULL;
932 		}
933 		count -= order_size;
934 		while (order_size--)
935 			pages[i++] = page++;
936 	}
937 	return pages;
938 }
939 
940 /*
941  * If size is less than PAGE_SIZE, then a full CPU page will be allocated,
942  * but an IOMMU which supports smaller pages might not map the whole thing.
943  */
__iommu_dma_alloc_noncontiguous(struct device * dev,size_t size,struct sg_table * sgt,gfp_t gfp,unsigned long attrs)944 static struct page **__iommu_dma_alloc_noncontiguous(struct device *dev,
945 		size_t size, struct sg_table *sgt, gfp_t gfp, unsigned long attrs)
946 {
947 	struct iommu_domain *domain = iommu_get_dma_domain(dev);
948 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
949 	struct iova_domain *iovad = &cookie->iovad;
950 	bool coherent = dev_is_dma_coherent(dev);
951 	int ioprot = dma_info_to_prot(DMA_BIDIRECTIONAL, coherent, attrs);
952 	unsigned int count, min_size, alloc_sizes = domain->pgsize_bitmap;
953 	struct page **pages;
954 	dma_addr_t iova;
955 	ssize_t ret;
956 
957 	if (static_branch_unlikely(&iommu_deferred_attach_enabled) &&
958 	    iommu_deferred_attach(dev, domain))
959 		return NULL;
960 
961 	min_size = alloc_sizes & -alloc_sizes;
962 	if (min_size < PAGE_SIZE) {
963 		min_size = PAGE_SIZE;
964 		alloc_sizes |= PAGE_SIZE;
965 	} else {
966 		size = ALIGN(size, min_size);
967 	}
968 	if (attrs & DMA_ATTR_ALLOC_SINGLE_PAGES)
969 		alloc_sizes = min_size;
970 
971 	count = PAGE_ALIGN(size) >> PAGE_SHIFT;
972 	pages = __iommu_dma_alloc_pages(dev, count, alloc_sizes >> PAGE_SHIFT,
973 					gfp);
974 	if (!pages)
975 		return NULL;
976 
977 	size = iova_align(iovad, size);
978 	iova = iommu_dma_alloc_iova(domain, size, dev->coherent_dma_mask, dev);
979 	if (!iova)
980 		goto out_free_pages;
981 
982 	/*
983 	 * Remove the zone/policy flags from the GFP - these are applied to the
984 	 * __iommu_dma_alloc_pages() but are not used for the supporting
985 	 * internal allocations that follow.
986 	 */
987 	gfp &= ~(__GFP_DMA | __GFP_DMA32 | __GFP_HIGHMEM | __GFP_COMP);
988 
989 	if (sg_alloc_table_from_pages(sgt, pages, count, 0, size, gfp))
990 		goto out_free_iova;
991 
992 	if (!(ioprot & IOMMU_CACHE)) {
993 		struct scatterlist *sg;
994 		int i;
995 
996 		for_each_sg(sgt->sgl, sg, sgt->orig_nents, i)
997 			arch_dma_prep_coherent(sg_page(sg), sg->length);
998 	}
999 
1000 	ret = iommu_map_sg(domain, iova, sgt->sgl, sgt->orig_nents, ioprot,
1001 			   gfp);
1002 	if (ret < 0 || ret < size)
1003 		goto out_free_sg;
1004 
1005 	sgt->sgl->dma_address = iova;
1006 	sgt->sgl->dma_length = size;
1007 	return pages;
1008 
1009 out_free_sg:
1010 	sg_free_table(sgt);
1011 out_free_iova:
1012 	iommu_dma_free_iova(cookie, iova, size, NULL);
1013 out_free_pages:
1014 	__iommu_dma_free_pages(pages, count);
1015 	return NULL;
1016 }
1017 
iommu_dma_alloc_remap(struct device * dev,size_t size,dma_addr_t * dma_handle,gfp_t gfp,unsigned long attrs)1018 static void *iommu_dma_alloc_remap(struct device *dev, size_t size,
1019 		dma_addr_t *dma_handle, gfp_t gfp, unsigned long attrs)
1020 {
1021 	struct page **pages;
1022 	struct sg_table sgt;
1023 	void *vaddr;
1024 	pgprot_t prot = dma_pgprot(dev, PAGE_KERNEL, attrs);
1025 
1026 	pages = __iommu_dma_alloc_noncontiguous(dev, size, &sgt, gfp, attrs);
1027 	if (!pages)
1028 		return NULL;
1029 	*dma_handle = sgt.sgl->dma_address;
1030 	sg_free_table(&sgt);
1031 	vaddr = dma_common_pages_remap(pages, size, prot,
1032 			__builtin_return_address(0));
1033 	if (!vaddr)
1034 		goto out_unmap;
1035 	return vaddr;
1036 
1037 out_unmap:
1038 	__iommu_dma_unmap(dev, *dma_handle, size);
1039 	__iommu_dma_free_pages(pages, PAGE_ALIGN(size) >> PAGE_SHIFT);
1040 	return NULL;
1041 }
1042 
1043 /*
1044  * This is the actual return value from the iommu_dma_alloc_noncontiguous.
1045  *
1046  * The users of the DMA API should only care about the sg_table, but to make
1047  * the DMA-API internal vmaping and freeing easier we stash away the page
1048  * array as well (except for the fallback case).  This can go away any time,
1049  * e.g. when a vmap-variant that takes a scatterlist comes along.
1050  */
1051 struct dma_sgt_handle {
1052 	struct sg_table sgt;
1053 	struct page **pages;
1054 };
1055 #define sgt_handle(sgt) \
1056 	container_of((sgt), struct dma_sgt_handle, sgt)
1057 
iommu_dma_alloc_noncontiguous(struct device * dev,size_t size,enum dma_data_direction dir,gfp_t gfp,unsigned long attrs)1058 struct sg_table *iommu_dma_alloc_noncontiguous(struct device *dev, size_t size,
1059 	       enum dma_data_direction dir, gfp_t gfp, unsigned long attrs)
1060 {
1061 	struct dma_sgt_handle *sh;
1062 
1063 	sh = kmalloc(sizeof(*sh), gfp);
1064 	if (!sh)
1065 		return NULL;
1066 
1067 	sh->pages = __iommu_dma_alloc_noncontiguous(dev, size, &sh->sgt, gfp, attrs);
1068 	if (!sh->pages) {
1069 		kfree(sh);
1070 		return NULL;
1071 	}
1072 	return &sh->sgt;
1073 }
1074 
iommu_dma_free_noncontiguous(struct device * dev,size_t size,struct sg_table * sgt,enum dma_data_direction dir)1075 void iommu_dma_free_noncontiguous(struct device *dev, size_t size,
1076 		struct sg_table *sgt, enum dma_data_direction dir)
1077 {
1078 	struct dma_sgt_handle *sh = sgt_handle(sgt);
1079 
1080 	__iommu_dma_unmap(dev, sgt->sgl->dma_address, size);
1081 	__iommu_dma_free_pages(sh->pages, PAGE_ALIGN(size) >> PAGE_SHIFT);
1082 	sg_free_table(&sh->sgt);
1083 	kfree(sh);
1084 }
1085 
iommu_dma_vmap_noncontiguous(struct device * dev,size_t size,struct sg_table * sgt)1086 void *iommu_dma_vmap_noncontiguous(struct device *dev, size_t size,
1087 		struct sg_table *sgt)
1088 {
1089 	unsigned long count = PAGE_ALIGN(size) >> PAGE_SHIFT;
1090 
1091 	return vmap(sgt_handle(sgt)->pages, count, VM_MAP, PAGE_KERNEL);
1092 }
1093 
iommu_dma_mmap_noncontiguous(struct device * dev,struct vm_area_struct * vma,size_t size,struct sg_table * sgt)1094 int iommu_dma_mmap_noncontiguous(struct device *dev, struct vm_area_struct *vma,
1095 		size_t size, struct sg_table *sgt)
1096 {
1097 	unsigned long count = PAGE_ALIGN(size) >> PAGE_SHIFT;
1098 
1099 	if (vma->vm_pgoff >= count || vma_pages(vma) > count - vma->vm_pgoff)
1100 		return -ENXIO;
1101 	return vm_map_pages(vma, sgt_handle(sgt)->pages, count);
1102 }
1103 
iommu_dma_sync_single_for_cpu(struct device * dev,dma_addr_t dma_handle,size_t size,enum dma_data_direction dir)1104 void iommu_dma_sync_single_for_cpu(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 	if (!dev_is_dma_coherent(dev))
1114 		arch_sync_dma_for_cpu(phys, size, dir);
1115 
1116 	swiotlb_sync_single_for_cpu(dev, phys, size, dir);
1117 }
1118 
iommu_dma_sync_single_for_device(struct device * dev,dma_addr_t dma_handle,size_t size,enum dma_data_direction dir)1119 void iommu_dma_sync_single_for_device(struct device *dev, dma_addr_t dma_handle,
1120 		size_t size, enum dma_data_direction dir)
1121 {
1122 	phys_addr_t phys;
1123 
1124 	if (dev_is_dma_coherent(dev) && !dev_use_swiotlb(dev, size, dir))
1125 		return;
1126 
1127 	phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle);
1128 	swiotlb_sync_single_for_device(dev, phys, size, dir);
1129 
1130 	if (!dev_is_dma_coherent(dev))
1131 		arch_sync_dma_for_device(phys, size, dir);
1132 }
1133 
iommu_dma_sync_sg_for_cpu(struct device * dev,struct scatterlist * sgl,int nelems,enum dma_data_direction dir)1134 void iommu_dma_sync_sg_for_cpu(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_cpu(dev, sg_dma_address(sg),
1143 						      sg->length, dir);
1144 	else if (!dev_is_dma_coherent(dev))
1145 		for_each_sg(sgl, sg, nelems, i)
1146 			arch_sync_dma_for_cpu(sg_phys(sg), sg->length, dir);
1147 }
1148 
iommu_dma_sync_sg_for_device(struct device * dev,struct scatterlist * sgl,int nelems,enum dma_data_direction dir)1149 void iommu_dma_sync_sg_for_device(struct device *dev, struct scatterlist *sgl,
1150 		int nelems, enum dma_data_direction dir)
1151 {
1152 	struct scatterlist *sg;
1153 	int i;
1154 
1155 	if (sg_dma_is_swiotlb(sgl))
1156 		for_each_sg(sgl, sg, nelems, i)
1157 			iommu_dma_sync_single_for_device(dev,
1158 							 sg_dma_address(sg),
1159 							 sg->length, dir);
1160 	else if (!dev_is_dma_coherent(dev))
1161 		for_each_sg(sgl, sg, nelems, i)
1162 			arch_sync_dma_for_device(sg_phys(sg), sg->length, dir);
1163 }
1164 
iommu_dma_map_page(struct device * dev,struct page * page,unsigned long offset,size_t size,enum dma_data_direction dir,unsigned long attrs)1165 dma_addr_t iommu_dma_map_page(struct device *dev, struct page *page,
1166 	      unsigned long offset, size_t size, enum dma_data_direction dir,
1167 	      unsigned long attrs)
1168 {
1169 	phys_addr_t phys = page_to_phys(page) + offset;
1170 	bool coherent = dev_is_dma_coherent(dev);
1171 	int prot = dma_info_to_prot(dir, coherent, attrs);
1172 	struct iommu_domain *domain = iommu_get_dma_domain(dev);
1173 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
1174 	struct iova_domain *iovad = &cookie->iovad;
1175 	dma_addr_t iova, dma_mask = dma_get_mask(dev);
1176 
1177 	/*
1178 	 * If both the physical buffer start address and size are
1179 	 * page aligned, we don't need to use a bounce page.
1180 	 */
1181 	if (dev_use_swiotlb(dev, size, dir) &&
1182 	    iova_offset(iovad, phys | size)) {
1183 		if (!is_swiotlb_active(dev)) {
1184 			dev_warn_once(dev, "DMA bounce buffers are inactive, unable to map unaligned transaction.\n");
1185 			return DMA_MAPPING_ERROR;
1186 		}
1187 
1188 		trace_swiotlb_bounced(dev, phys, size);
1189 
1190 		phys = swiotlb_tbl_map_single(dev, phys, size,
1191 					      iova_mask(iovad), dir, attrs);
1192 
1193 		if (phys == DMA_MAPPING_ERROR)
1194 			return DMA_MAPPING_ERROR;
1195 
1196 		/*
1197 		 * Untrusted devices should not see padding areas with random
1198 		 * leftover kernel data, so zero the pre- and post-padding.
1199 		 * swiotlb_tbl_map_single() has initialized the bounce buffer
1200 		 * proper to the contents of the original memory buffer.
1201 		 */
1202 		if (dev_is_untrusted(dev)) {
1203 			size_t start, virt = (size_t)phys_to_virt(phys);
1204 
1205 			/* Pre-padding */
1206 			start = iova_align_down(iovad, virt);
1207 			memset((void *)start, 0, virt - start);
1208 
1209 			/* Post-padding */
1210 			start = virt + size;
1211 			memset((void *)start, 0,
1212 			       iova_align(iovad, start) - start);
1213 		}
1214 	}
1215 
1216 	if (!coherent && !(attrs & DMA_ATTR_SKIP_CPU_SYNC))
1217 		arch_sync_dma_for_device(phys, size, dir);
1218 
1219 	iova = __iommu_dma_map(dev, phys, size, prot, dma_mask);
1220 	if (iova == DMA_MAPPING_ERROR)
1221 		swiotlb_tbl_unmap_single(dev, phys, size, dir, attrs);
1222 	return iova;
1223 }
1224 
iommu_dma_unmap_page(struct device * dev,dma_addr_t dma_handle,size_t size,enum dma_data_direction dir,unsigned long attrs)1225 void iommu_dma_unmap_page(struct device *dev, dma_addr_t dma_handle,
1226 		size_t size, enum dma_data_direction dir, unsigned long attrs)
1227 {
1228 	struct iommu_domain *domain = iommu_get_dma_domain(dev);
1229 	phys_addr_t phys;
1230 
1231 	phys = iommu_iova_to_phys(domain, dma_handle);
1232 	if (WARN_ON(!phys))
1233 		return;
1234 
1235 	if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) && !dev_is_dma_coherent(dev))
1236 		arch_sync_dma_for_cpu(phys, size, dir);
1237 
1238 	__iommu_dma_unmap(dev, dma_handle, size);
1239 
1240 	swiotlb_tbl_unmap_single(dev, phys, size, dir, attrs);
1241 }
1242 
1243 /*
1244  * Prepare a successfully-mapped scatterlist to give back to the caller.
1245  *
1246  * At this point the segments are already laid out by iommu_dma_map_sg() to
1247  * avoid individually crossing any boundaries, so we merely need to check a
1248  * segment's start address to avoid concatenating across one.
1249  */
__finalise_sg(struct device * dev,struct scatterlist * sg,int nents,dma_addr_t dma_addr)1250 static int __finalise_sg(struct device *dev, struct scatterlist *sg, int nents,
1251 		dma_addr_t dma_addr)
1252 {
1253 	struct scatterlist *s, *cur = sg;
1254 	unsigned long seg_mask = dma_get_seg_boundary(dev);
1255 	unsigned int cur_len = 0, max_len = dma_get_max_seg_size(dev);
1256 	int i, count = 0;
1257 
1258 	for_each_sg(sg, s, nents, i) {
1259 		/* Restore this segment's original unaligned fields first */
1260 		dma_addr_t s_dma_addr = sg_dma_address(s);
1261 		unsigned int s_iova_off = sg_dma_address(s);
1262 		unsigned int s_length = sg_dma_len(s);
1263 		unsigned int s_iova_len = s->length;
1264 
1265 		sg_dma_address(s) = DMA_MAPPING_ERROR;
1266 		sg_dma_len(s) = 0;
1267 
1268 		if (sg_dma_is_bus_address(s)) {
1269 			if (i > 0)
1270 				cur = sg_next(cur);
1271 
1272 			sg_dma_unmark_bus_address(s);
1273 			sg_dma_address(cur) = s_dma_addr;
1274 			sg_dma_len(cur) = s_length;
1275 			sg_dma_mark_bus_address(cur);
1276 			count++;
1277 			cur_len = 0;
1278 			continue;
1279 		}
1280 
1281 		s->offset += s_iova_off;
1282 		s->length = s_length;
1283 
1284 		/*
1285 		 * Now fill in the real DMA data. If...
1286 		 * - there is a valid output segment to append to
1287 		 * - and this segment starts on an IOVA page boundary
1288 		 * - but doesn't fall at a segment boundary
1289 		 * - and wouldn't make the resulting output segment too long
1290 		 */
1291 		if (cur_len && !s_iova_off && (dma_addr & seg_mask) &&
1292 		    (max_len - cur_len >= s_length)) {
1293 			/* ...then concatenate it with the previous one */
1294 			cur_len += s_length;
1295 		} else {
1296 			/* Otherwise start the next output segment */
1297 			if (i > 0)
1298 				cur = sg_next(cur);
1299 			cur_len = s_length;
1300 			count++;
1301 
1302 			sg_dma_address(cur) = dma_addr + s_iova_off;
1303 		}
1304 
1305 		sg_dma_len(cur) = cur_len;
1306 		dma_addr += s_iova_len;
1307 
1308 		if (s_length + s_iova_off < s_iova_len)
1309 			cur_len = 0;
1310 	}
1311 	return count;
1312 }
1313 
1314 /*
1315  * If mapping failed, then just restore the original list,
1316  * but making sure the DMA fields are invalidated.
1317  */
__invalidate_sg(struct scatterlist * sg,int nents)1318 static void __invalidate_sg(struct scatterlist *sg, int nents)
1319 {
1320 	struct scatterlist *s;
1321 	int i;
1322 
1323 	for_each_sg(sg, s, nents, i) {
1324 		if (sg_dma_is_bus_address(s)) {
1325 			sg_dma_unmark_bus_address(s);
1326 		} else {
1327 			if (sg_dma_address(s) != DMA_MAPPING_ERROR)
1328 				s->offset += sg_dma_address(s);
1329 			if (sg_dma_len(s))
1330 				s->length = sg_dma_len(s);
1331 		}
1332 		sg_dma_address(s) = DMA_MAPPING_ERROR;
1333 		sg_dma_len(s) = 0;
1334 	}
1335 }
1336 
iommu_dma_unmap_sg_swiotlb(struct device * dev,struct scatterlist * sg,int nents,enum dma_data_direction dir,unsigned long attrs)1337 static void iommu_dma_unmap_sg_swiotlb(struct device *dev, struct scatterlist *sg,
1338 		int nents, enum dma_data_direction dir, unsigned long attrs)
1339 {
1340 	struct scatterlist *s;
1341 	int i;
1342 
1343 	for_each_sg(sg, s, nents, i)
1344 		iommu_dma_unmap_page(dev, sg_dma_address(s),
1345 				sg_dma_len(s), dir, attrs);
1346 }
1347 
iommu_dma_map_sg_swiotlb(struct device * dev,struct scatterlist * sg,int nents,enum dma_data_direction dir,unsigned long attrs)1348 static int iommu_dma_map_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 	sg_dma_mark_swiotlb(sg);
1355 
1356 	for_each_sg(sg, s, nents, i) {
1357 		sg_dma_address(s) = iommu_dma_map_page(dev, sg_page(s),
1358 				s->offset, s->length, dir, attrs);
1359 		if (sg_dma_address(s) == DMA_MAPPING_ERROR)
1360 			goto out_unmap;
1361 		sg_dma_len(s) = s->length;
1362 	}
1363 
1364 	return nents;
1365 
1366 out_unmap:
1367 	iommu_dma_unmap_sg_swiotlb(dev, sg, i, dir, attrs | DMA_ATTR_SKIP_CPU_SYNC);
1368 	return -EIO;
1369 }
1370 
1371 /*
1372  * The DMA API client is passing in a scatterlist which could describe
1373  * any old buffer layout, but the IOMMU API requires everything to be
1374  * aligned to IOMMU pages. Hence the need for this complicated bit of
1375  * impedance-matching, to be able to hand off a suitably-aligned list,
1376  * but still preserve the original offsets and sizes for the caller.
1377  */
iommu_dma_map_sg(struct device * dev,struct scatterlist * sg,int nents,enum dma_data_direction dir,unsigned long attrs)1378 int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
1379 		enum dma_data_direction dir, unsigned long attrs)
1380 {
1381 	struct iommu_domain *domain = iommu_get_dma_domain(dev);
1382 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
1383 	struct iova_domain *iovad = &cookie->iovad;
1384 	struct scatterlist *s, *prev = NULL;
1385 	int prot = dma_info_to_prot(dir, dev_is_dma_coherent(dev), attrs);
1386 	struct pci_p2pdma_map_state p2pdma_state = {};
1387 	enum pci_p2pdma_map_type map;
1388 	dma_addr_t iova;
1389 	size_t iova_len = 0;
1390 	unsigned long mask = dma_get_seg_boundary(dev);
1391 	ssize_t ret;
1392 	int i;
1393 
1394 	if (static_branch_unlikely(&iommu_deferred_attach_enabled)) {
1395 		ret = iommu_deferred_attach(dev, domain);
1396 		if (ret)
1397 			goto out;
1398 	}
1399 
1400 	if (dev_use_sg_swiotlb(dev, sg, nents, dir))
1401 		return iommu_dma_map_sg_swiotlb(dev, sg, nents, dir, attrs);
1402 
1403 	if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
1404 		iommu_dma_sync_sg_for_device(dev, sg, nents, dir);
1405 
1406 	/*
1407 	 * Work out how much IOVA space we need, and align the segments to
1408 	 * IOVA granules for the IOMMU driver to handle. With some clever
1409 	 * trickery we can modify the list in-place, but reversibly, by
1410 	 * stashing the unaligned parts in the as-yet-unused DMA fields.
1411 	 */
1412 	for_each_sg(sg, s, nents, i) {
1413 		size_t s_iova_off = iova_offset(iovad, s->offset);
1414 		size_t s_length = s->length;
1415 		size_t pad_len = (mask - iova_len + 1) & mask;
1416 
1417 		if (is_pci_p2pdma_page(sg_page(s))) {
1418 			map = pci_p2pdma_map_segment(&p2pdma_state, dev, s);
1419 			switch (map) {
1420 			case PCI_P2PDMA_MAP_BUS_ADDR:
1421 				/*
1422 				 * iommu_map_sg() will skip this segment as
1423 				 * it is marked as a bus address,
1424 				 * __finalise_sg() will copy the dma address
1425 				 * into the output segment.
1426 				 */
1427 				continue;
1428 			case PCI_P2PDMA_MAP_THRU_HOST_BRIDGE:
1429 				/*
1430 				 * Mapping through host bridge should be
1431 				 * mapped with regular IOVAs, thus we
1432 				 * do nothing here and continue below.
1433 				 */
1434 				break;
1435 			default:
1436 				ret = -EREMOTEIO;
1437 				goto out_restore_sg;
1438 			}
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(cookie, 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 
iommu_dma_unmap_sg(struct device * dev,struct scatterlist * sg,int nents,enum dma_data_direction dir,unsigned long attrs)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 
iommu_dma_map_resource(struct device * dev,phys_addr_t phys,size_t size,enum dma_data_direction dir,unsigned long attrs)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 
iommu_dma_unmap_resource(struct device * dev,dma_addr_t handle,size_t size,enum dma_data_direction dir,unsigned long attrs)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 
__iommu_dma_free(struct device * dev,size_t size,void * cpu_addr)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 
iommu_dma_free(struct device * dev,size_t size,void * cpu_addr,dma_addr_t handle,unsigned long attrs)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 
iommu_dma_alloc_pages(struct device * dev,size_t size,struct page ** pagep,gfp_t gfp,unsigned long attrs)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 
iommu_dma_alloc(struct device * dev,size_t size,dma_addr_t * handle,gfp_t gfp,unsigned long attrs)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 
iommu_dma_mmap(struct device * dev,struct vm_area_struct * vma,void * cpu_addr,dma_addr_t dma_addr,size_t size,unsigned long attrs)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 
iommu_dma_get_sgtable(struct device * dev,struct sg_table * sgt,void * cpu_addr,dma_addr_t dma_addr,size_t size,unsigned long attrs)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 
iommu_dma_get_merge_boundary(struct device * dev)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 
iommu_dma_opt_mapping_size(void)1736 size_t iommu_dma_opt_mapping_size(void)
1737 {
1738 	return iova_rcache_range();
1739 }
1740 
iommu_dma_max_mapping_size(struct device * dev)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 
iommu_setup_dma_ops(struct device * dev)1749 void iommu_setup_dma_ops(struct device *dev)
1750 {
1751 	struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
1752 
1753 	if (dev_is_pci(dev))
1754 		dev->iommu->pci_32bit_workaround = !iommu_dma_forcedac;
1755 
1756 	dev->dma_iommu = iommu_is_dma_domain(domain);
1757 	if (dev->dma_iommu && iommu_dma_init_domain(domain, dev))
1758 		goto out_err;
1759 
1760 	return;
1761 out_err:
1762 	pr_warn("Failed to set up IOMMU for device %s; retaining platform DMA ops\n",
1763 		dev_name(dev));
1764 	dev->dma_iommu = false;
1765 }
1766 
iommu_dma_get_msi_page(struct device * dev,phys_addr_t msi_addr,struct iommu_domain * domain)1767 static struct iommu_dma_msi_page *iommu_dma_get_msi_page(struct device *dev,
1768 		phys_addr_t msi_addr, struct iommu_domain *domain)
1769 {
1770 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
1771 	struct iommu_dma_msi_page *msi_page;
1772 	dma_addr_t iova;
1773 	int prot = IOMMU_WRITE | IOMMU_NOEXEC | IOMMU_MMIO;
1774 	size_t size = cookie_msi_granule(cookie);
1775 
1776 	msi_addr &= ~(phys_addr_t)(size - 1);
1777 	list_for_each_entry(msi_page, &cookie->msi_page_list, list)
1778 		if (msi_page->phys == msi_addr)
1779 			return msi_page;
1780 
1781 	msi_page = kzalloc(sizeof(*msi_page), GFP_KERNEL);
1782 	if (!msi_page)
1783 		return NULL;
1784 
1785 	iova = iommu_dma_alloc_iova(domain, size, dma_get_mask(dev), dev);
1786 	if (!iova)
1787 		goto out_free_page;
1788 
1789 	if (iommu_map(domain, iova, msi_addr, size, prot, GFP_KERNEL))
1790 		goto out_free_iova;
1791 
1792 	INIT_LIST_HEAD(&msi_page->list);
1793 	msi_page->phys = msi_addr;
1794 	msi_page->iova = iova;
1795 	list_add(&msi_page->list, &cookie->msi_page_list);
1796 	return msi_page;
1797 
1798 out_free_iova:
1799 	iommu_dma_free_iova(cookie, iova, size, NULL);
1800 out_free_page:
1801 	kfree(msi_page);
1802 	return NULL;
1803 }
1804 
iommu_dma_sw_msi(struct iommu_domain * domain,struct msi_desc * desc,phys_addr_t msi_addr)1805 static int iommu_dma_sw_msi(struct iommu_domain *domain, struct msi_desc *desc,
1806 			    phys_addr_t msi_addr)
1807 {
1808 	struct device *dev = msi_desc_to_dev(desc);
1809 	const struct iommu_dma_msi_page *msi_page;
1810 
1811 	if (!domain->iova_cookie) {
1812 		msi_desc_set_iommu_msi_iova(desc, 0, 0);
1813 		return 0;
1814 	}
1815 
1816 	iommu_group_mutex_assert(dev);
1817 	msi_page = iommu_dma_get_msi_page(dev, msi_addr, domain);
1818 	if (!msi_page)
1819 		return -ENOMEM;
1820 
1821 	msi_desc_set_iommu_msi_iova(
1822 		desc, msi_page->iova,
1823 		ilog2(cookie_msi_granule(domain->iova_cookie)));
1824 	return 0;
1825 }
1826 
iommu_dma_init(void)1827 static int iommu_dma_init(void)
1828 {
1829 	if (is_kdump_kernel())
1830 		static_branch_enable(&iommu_deferred_attach_enabled);
1831 
1832 	return iova_cache_get();
1833 }
1834 arch_initcall(iommu_dma_init);
1835