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