• 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/device.h>
13 #include <linux/dma-contiguous.h>
14 #include <linux/dma-iommu.h>
15 #include <linux/dma-noncoherent.h>
16 #include <linux/gfp.h>
17 #include <linux/huge_mm.h>
18 #include <linux/iommu.h>
19 #include <linux/iova.h>
20 #include <linux/irq.h>
21 #include <linux/mm.h>
22 #include <linux/mutex.h>
23 #include <linux/pci.h>
24 #include <linux/scatterlist.h>
25 #include <linux/vmalloc.h>
26 
27 struct iommu_dma_msi_page {
28 	struct list_head	list;
29 	dma_addr_t		iova;
30 	phys_addr_t		phys;
31 };
32 
33 enum iommu_dma_cookie_type {
34 	IOMMU_DMA_IOVA_COOKIE,
35 	IOMMU_DMA_MSI_COOKIE,
36 };
37 
38 struct iommu_dma_cookie {
39 	enum iommu_dma_cookie_type	type;
40 	union {
41 		/* Full allocator for IOMMU_DMA_IOVA_COOKIE */
42 		struct iova_domain	iovad;
43 		/* Trivial linear page allocator for IOMMU_DMA_MSI_COOKIE */
44 		dma_addr_t		msi_iova;
45 	};
46 	struct list_head		msi_page_list;
47 
48 	/* Domain for flush queue callback; NULL if flush queue not in use */
49 	struct iommu_domain		*fq_domain;
50 };
51 
cookie_msi_granule(struct iommu_dma_cookie * cookie)52 static inline size_t cookie_msi_granule(struct iommu_dma_cookie *cookie)
53 {
54 	if (cookie->type == IOMMU_DMA_IOVA_COOKIE)
55 		return cookie->iovad.granule;
56 	return PAGE_SIZE;
57 }
58 
cookie_alloc(enum iommu_dma_cookie_type type)59 static struct iommu_dma_cookie *cookie_alloc(enum iommu_dma_cookie_type type)
60 {
61 	struct iommu_dma_cookie *cookie;
62 
63 	cookie = kzalloc(sizeof(*cookie), GFP_KERNEL);
64 	if (cookie) {
65 		INIT_LIST_HEAD(&cookie->msi_page_list);
66 		cookie->type = type;
67 	}
68 	return cookie;
69 }
70 
71 /**
72  * iommu_get_dma_cookie - Acquire DMA-API resources for a domain
73  * @domain: IOMMU domain to prepare for DMA-API usage
74  *
75  * IOMMU drivers should normally call this from their domain_alloc
76  * callback when domain->type == IOMMU_DOMAIN_DMA.
77  */
iommu_get_dma_cookie(struct iommu_domain * domain)78 int iommu_get_dma_cookie(struct iommu_domain *domain)
79 {
80 	if (domain->iova_cookie)
81 		return -EEXIST;
82 
83 	domain->iova_cookie = cookie_alloc(IOMMU_DMA_IOVA_COOKIE);
84 	if (!domain->iova_cookie)
85 		return -ENOMEM;
86 
87 	return 0;
88 }
89 EXPORT_SYMBOL(iommu_get_dma_cookie);
90 
91 /**
92  * iommu_get_msi_cookie - Acquire just MSI remapping resources
93  * @domain: IOMMU domain to prepare
94  * @base: Start address of IOVA region for MSI mappings
95  *
96  * Users who manage their own IOVA allocation and do not want DMA API support,
97  * but would still like to take advantage of automatic MSI remapping, can use
98  * this to initialise their own domain appropriately. Users should reserve a
99  * contiguous IOVA region, starting at @base, large enough to accommodate the
100  * number of PAGE_SIZE mappings necessary to cover every MSI doorbell address
101  * used by the devices attached to @domain.
102  */
iommu_get_msi_cookie(struct iommu_domain * domain,dma_addr_t base)103 int iommu_get_msi_cookie(struct iommu_domain *domain, dma_addr_t base)
104 {
105 	struct iommu_dma_cookie *cookie;
106 
107 	if (domain->type != IOMMU_DOMAIN_UNMANAGED)
108 		return -EINVAL;
109 
110 	if (domain->iova_cookie)
111 		return -EEXIST;
112 
113 	cookie = cookie_alloc(IOMMU_DMA_MSI_COOKIE);
114 	if (!cookie)
115 		return -ENOMEM;
116 
117 	cookie->msi_iova = base;
118 	domain->iova_cookie = cookie;
119 	return 0;
120 }
121 EXPORT_SYMBOL(iommu_get_msi_cookie);
122 
123 /**
124  * iommu_put_dma_cookie - Release a domain's DMA mapping resources
125  * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie() or
126  *          iommu_get_msi_cookie()
127  *
128  * IOMMU drivers should normally call this from their domain_free callback.
129  */
iommu_put_dma_cookie(struct iommu_domain * domain)130 void iommu_put_dma_cookie(struct iommu_domain *domain)
131 {
132 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
133 	struct iommu_dma_msi_page *msi, *tmp;
134 
135 	if (!cookie)
136 		return;
137 
138 	if (cookie->type == IOMMU_DMA_IOVA_COOKIE && cookie->iovad.granule)
139 		put_iova_domain(&cookie->iovad);
140 
141 	list_for_each_entry_safe(msi, tmp, &cookie->msi_page_list, list) {
142 		list_del(&msi->list);
143 		kfree(msi);
144 	}
145 	kfree(cookie);
146 	domain->iova_cookie = NULL;
147 }
148 EXPORT_SYMBOL(iommu_put_dma_cookie);
149 
150 /**
151  * iommu_dma_get_resv_regions - Reserved region driver helper
152  * @dev: Device from iommu_get_resv_regions()
153  * @list: Reserved region list from iommu_get_resv_regions()
154  *
155  * IOMMU drivers can use this to implement their .get_resv_regions callback
156  * for general non-IOMMU-specific reservations. Currently, this covers GICv3
157  * ITS region reservation on ACPI based ARM platforms that may require HW MSI
158  * reservation.
159  */
iommu_dma_get_resv_regions(struct device * dev,struct list_head * list)160 void iommu_dma_get_resv_regions(struct device *dev, struct list_head *list)
161 {
162 
163 	if (!is_of_node(dev_iommu_fwspec_get(dev)->iommu_fwnode))
164 		iort_iommu_msi_get_resv_regions(dev, list);
165 
166 }
167 EXPORT_SYMBOL(iommu_dma_get_resv_regions);
168 
cookie_init_hw_msi_region(struct iommu_dma_cookie * cookie,phys_addr_t start,phys_addr_t end)169 static int cookie_init_hw_msi_region(struct iommu_dma_cookie *cookie,
170 		phys_addr_t start, phys_addr_t end)
171 {
172 	struct iova_domain *iovad = &cookie->iovad;
173 	struct iommu_dma_msi_page *msi_page;
174 	int i, num_pages;
175 
176 	start -= iova_offset(iovad, start);
177 	num_pages = iova_align(iovad, end - start) >> iova_shift(iovad);
178 
179 	for (i = 0; i < num_pages; i++) {
180 		msi_page = kmalloc(sizeof(*msi_page), GFP_KERNEL);
181 		if (!msi_page)
182 			return -ENOMEM;
183 
184 		msi_page->phys = start;
185 		msi_page->iova = start;
186 		INIT_LIST_HEAD(&msi_page->list);
187 		list_add(&msi_page->list, &cookie->msi_page_list);
188 		start += iovad->granule;
189 	}
190 
191 	return 0;
192 }
193 
iova_reserve_pci_windows(struct pci_dev * dev,struct iova_domain * iovad)194 static int iova_reserve_pci_windows(struct pci_dev *dev,
195 		struct iova_domain *iovad)
196 {
197 	struct pci_host_bridge *bridge = pci_find_host_bridge(dev->bus);
198 	struct resource_entry *window;
199 	unsigned long lo, hi;
200 	phys_addr_t start = 0, end;
201 
202 	resource_list_for_each_entry(window, &bridge->windows) {
203 		if (resource_type(window->res) != IORESOURCE_MEM)
204 			continue;
205 
206 		lo = iova_pfn(iovad, window->res->start - window->offset);
207 		hi = iova_pfn(iovad, window->res->end - window->offset);
208 		reserve_iova(iovad, lo, hi);
209 	}
210 
211 	/* Get reserved DMA windows from host bridge */
212 	resource_list_for_each_entry(window, &bridge->dma_ranges) {
213 		end = window->res->start - window->offset;
214 resv_iova:
215 		if (end > start) {
216 			lo = iova_pfn(iovad, start);
217 			hi = iova_pfn(iovad, end);
218 			reserve_iova(iovad, lo, hi);
219 		} else if (end < start) {
220 			/* dma_ranges list should be sorted */
221 			dev_err(&dev->dev,
222 				"Failed to reserve IOVA [%pa-%pa]\n",
223 				&start, &end);
224 			return -EINVAL;
225 		}
226 
227 		start = window->res->end - window->offset + 1;
228 		/* If window is last entry */
229 		if (window->node.next == &bridge->dma_ranges &&
230 		    end != ~(phys_addr_t)0) {
231 			end = ~(phys_addr_t)0;
232 			goto resv_iova;
233 		}
234 	}
235 
236 	return 0;
237 }
238 
iova_reserve_iommu_regions(struct device * dev,struct iommu_domain * domain)239 static int iova_reserve_iommu_regions(struct device *dev,
240 		struct iommu_domain *domain)
241 {
242 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
243 	struct iova_domain *iovad = &cookie->iovad;
244 	struct iommu_resv_region *region;
245 	LIST_HEAD(resv_regions);
246 	int ret = 0;
247 
248 	if (dev_is_pci(dev)) {
249 		ret = iova_reserve_pci_windows(to_pci_dev(dev), iovad);
250 		if (ret)
251 			return ret;
252 	}
253 
254 	iommu_get_resv_regions(dev, &resv_regions);
255 	list_for_each_entry(region, &resv_regions, list) {
256 		unsigned long lo, hi;
257 
258 		/* We ARE the software that manages these! */
259 		if (region->type == IOMMU_RESV_SW_MSI)
260 			continue;
261 
262 		lo = iova_pfn(iovad, region->start);
263 		hi = iova_pfn(iovad, region->start + region->length - 1);
264 		reserve_iova(iovad, lo, hi);
265 
266 		if (region->type == IOMMU_RESV_MSI)
267 			ret = cookie_init_hw_msi_region(cookie, region->start,
268 					region->start + region->length);
269 		if (ret)
270 			break;
271 	}
272 	iommu_put_resv_regions(dev, &resv_regions);
273 
274 	return ret;
275 }
276 
iommu_dma_flush_iotlb_all(struct iova_domain * iovad)277 static void iommu_dma_flush_iotlb_all(struct iova_domain *iovad)
278 {
279 	struct iommu_dma_cookie *cookie;
280 	struct iommu_domain *domain;
281 
282 	cookie = container_of(iovad, struct iommu_dma_cookie, iovad);
283 	domain = cookie->fq_domain;
284 	/*
285 	 * The IOMMU driver supporting DOMAIN_ATTR_DMA_USE_FLUSH_QUEUE
286 	 * implies that ops->flush_iotlb_all must be non-NULL.
287 	 */
288 	domain->ops->flush_iotlb_all(domain);
289 }
290 
291 /**
292  * iommu_dma_init_domain - Initialise a DMA mapping domain
293  * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie()
294  * @base: IOVA at which the mappable address space starts
295  * @size: Size of IOVA space
296  * @dev: Device the domain is being initialised for
297  *
298  * @base and @size should be exact multiples of IOMMU page granularity to
299  * avoid rounding surprises. If necessary, we reserve the page at address 0
300  * to ensure it is an invalid IOVA. It is safe to reinitialise a domain, but
301  * any change which could make prior IOVAs invalid will fail.
302  */
iommu_dma_init_domain(struct iommu_domain * domain,dma_addr_t base,u64 size,struct device * dev)303 static int iommu_dma_init_domain(struct iommu_domain *domain, dma_addr_t base,
304 		u64 size, struct device *dev)
305 {
306 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
307 	unsigned long order, base_pfn;
308 	struct iova_domain *iovad;
309 	int attr;
310 
311 	if (!cookie || cookie->type != IOMMU_DMA_IOVA_COOKIE)
312 		return -EINVAL;
313 
314 	iovad = &cookie->iovad;
315 
316 	/* Use the smallest supported page size for IOVA granularity */
317 	order = __ffs(domain->pgsize_bitmap);
318 	base_pfn = max_t(unsigned long, 1, base >> order);
319 
320 	/* Check the domain allows at least some access to the device... */
321 	if (domain->geometry.force_aperture) {
322 		if (base > domain->geometry.aperture_end ||
323 		    base + size <= domain->geometry.aperture_start) {
324 			pr_warn("specified DMA range outside IOMMU capability\n");
325 			return -EFAULT;
326 		}
327 		/* ...then finally give it a kicking to make sure it fits */
328 		base_pfn = max_t(unsigned long, base_pfn,
329 				domain->geometry.aperture_start >> order);
330 	}
331 
332 	/* start_pfn is always nonzero for an already-initialised domain */
333 	if (iovad->start_pfn) {
334 		if (1UL << order != iovad->granule ||
335 		    base_pfn != iovad->start_pfn) {
336 			pr_warn("Incompatible range for DMA domain\n");
337 			return -EFAULT;
338 		}
339 
340 		return 0;
341 	}
342 
343 	init_iova_domain(iovad, 1UL << order, base_pfn);
344 
345 	if (!cookie->fq_domain && !iommu_domain_get_attr(domain,
346 			DOMAIN_ATTR_DMA_USE_FLUSH_QUEUE, &attr) && attr) {
347 		cookie->fq_domain = domain;
348 		init_iova_flush_queue(iovad, iommu_dma_flush_iotlb_all, NULL);
349 	}
350 
351 	if (!dev)
352 		return 0;
353 
354 	return iova_reserve_iommu_regions(dev, domain);
355 }
356 
357 /*
358  * Should be called prior to using dma-apis
359  */
iommu_dma_reserve_iova(struct device * dev,dma_addr_t base,u64 size)360 int iommu_dma_reserve_iova(struct device *dev, dma_addr_t base,
361 			   u64 size)
362 {
363 	struct iommu_domain *domain;
364 	struct iommu_dma_cookie *cookie;
365 	struct iova_domain *iovad;
366 	unsigned long pfn_lo, pfn_hi;
367 
368 	domain = iommu_get_domain_for_dev(dev);
369 	if (!domain || !domain->iova_cookie)
370 		return -EINVAL;
371 
372 	cookie = domain->iova_cookie;
373 	iovad = &cookie->iovad;
374 
375 	/* iova will be freed automatically by put_iova_domain() */
376 	pfn_lo = iova_pfn(iovad, base);
377 	pfn_hi = iova_pfn(iovad, base + size - 1);
378 	if (!reserve_iova(iovad, pfn_lo, pfn_hi))
379 		return -EINVAL;
380 
381 	return 0;
382 }
383 EXPORT_SYMBOL(iommu_dma_reserve_iova);
384 
385 /*
386  * Should be called prior to using dma-apis.
387  */
iommu_dma_enable_best_fit_algo(struct device * dev)388 int iommu_dma_enable_best_fit_algo(struct device *dev)
389 {
390 	struct iommu_domain *domain;
391 	struct iova_domain *iovad;
392 
393 	domain = iommu_get_domain_for_dev(dev);
394 	if (!domain || !domain->iova_cookie)
395 		return -EINVAL;
396 
397 	iovad = &((struct iommu_dma_cookie *)domain->iova_cookie)->iovad;
398 	iovad->best_fit = true;
399 	return 0;
400 }
401 EXPORT_SYMBOL(iommu_dma_enable_best_fit_algo);
402 
403 /**
404  * dma_info_to_prot - Translate DMA API directions and attributes to IOMMU API
405  *                    page flags.
406  * @dir: Direction of DMA transfer
407  * @coherent: Is the DMA master cache-coherent?
408  * @attrs: DMA attributes for the mapping
409  *
410  * Return: corresponding IOMMU API page protection flags
411  */
dma_info_to_prot(enum dma_data_direction dir,bool coherent,unsigned long attrs)412 static int dma_info_to_prot(enum dma_data_direction dir, bool coherent,
413 		     unsigned long attrs)
414 {
415 	int prot = coherent ? IOMMU_CACHE : 0;
416 
417 	if (attrs & DMA_ATTR_PRIVILEGED)
418 		prot |= IOMMU_PRIV;
419 
420 	switch (dir) {
421 	case DMA_BIDIRECTIONAL:
422 		return prot | IOMMU_READ | IOMMU_WRITE;
423 	case DMA_TO_DEVICE:
424 		return prot | IOMMU_READ;
425 	case DMA_FROM_DEVICE:
426 		return prot | IOMMU_WRITE;
427 	default:
428 		return 0;
429 	}
430 }
431 
iommu_dma_alloc_iova(struct iommu_domain * domain,size_t size,dma_addr_t dma_limit,struct device * dev)432 static dma_addr_t iommu_dma_alloc_iova(struct iommu_domain *domain,
433 		size_t size, dma_addr_t dma_limit, struct device *dev)
434 {
435 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
436 	struct iova_domain *iovad = &cookie->iovad;
437 	unsigned long shift, iova_len, iova = 0;
438 
439 	if (cookie->type == IOMMU_DMA_MSI_COOKIE) {
440 		cookie->msi_iova += size;
441 		return cookie->msi_iova - size;
442 	}
443 
444 	shift = iova_shift(iovad);
445 	iova_len = size >> shift;
446 	/*
447 	 * Freeing non-power-of-two-sized allocations back into the IOVA caches
448 	 * will come back to bite us badly, so we have to waste a bit of space
449 	 * rounding up anything cacheable to make sure that can't happen. The
450 	 * order of the unadjusted size will still match upon freeing.
451 	 */
452 	if (iova_len < (1 << (IOVA_RANGE_CACHE_MAX_SIZE - 1)))
453 		iova_len = roundup_pow_of_two(iova_len);
454 
455 	if (dev->bus_dma_mask)
456 		dma_limit &= dev->bus_dma_mask;
457 
458 	if (domain->geometry.force_aperture)
459 		dma_limit = min(dma_limit, domain->geometry.aperture_end);
460 
461 	/* Try to get PCI devices a SAC address */
462 	if (dma_limit > DMA_BIT_MASK(32) && dev_is_pci(dev))
463 		iova = alloc_iova_fast(iovad, iova_len,
464 				       DMA_BIT_MASK(32) >> shift, false);
465 
466 	if (!iova)
467 		iova = alloc_iova_fast(iovad, iova_len, dma_limit >> shift,
468 				       true);
469 
470 	return (dma_addr_t)iova << shift;
471 }
472 
iommu_dma_free_iova(struct iommu_dma_cookie * cookie,dma_addr_t iova,size_t size)473 static void iommu_dma_free_iova(struct iommu_dma_cookie *cookie,
474 		dma_addr_t iova, size_t size)
475 {
476 	struct iova_domain *iovad = &cookie->iovad;
477 
478 	/* The MSI case is only ever cleaning up its most recent allocation */
479 	if (cookie->type == IOMMU_DMA_MSI_COOKIE)
480 		cookie->msi_iova -= size;
481 	else if (cookie->fq_domain)	/* non-strict mode */
482 		queue_iova(iovad, iova_pfn(iovad, iova),
483 				size >> iova_shift(iovad), 0);
484 	else
485 		free_iova_fast(iovad, iova_pfn(iovad, iova),
486 				size >> iova_shift(iovad));
487 }
488 
__iommu_dma_unmap(struct device * dev,dma_addr_t dma_addr,size_t size)489 static void __iommu_dma_unmap(struct device *dev, dma_addr_t dma_addr,
490 		size_t size)
491 {
492 	struct iommu_domain *domain = iommu_get_dma_domain(dev);
493 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
494 	struct iova_domain *iovad = &cookie->iovad;
495 	size_t iova_off = iova_offset(iovad, dma_addr);
496 	struct iommu_iotlb_gather iotlb_gather;
497 	size_t unmapped;
498 
499 	dma_addr -= iova_off;
500 	size = iova_align(iovad, size + iova_off);
501 	iommu_iotlb_gather_init(&iotlb_gather);
502 
503 	unmapped = iommu_unmap_fast(domain, dma_addr, size, &iotlb_gather);
504 	WARN_ON(unmapped != size);
505 
506 	if (!cookie->fq_domain)
507 		iommu_tlb_sync(domain, &iotlb_gather);
508 	iommu_dma_free_iova(cookie, dma_addr, size);
509 }
510 
__iommu_dma_map(struct device * dev,phys_addr_t phys,size_t size,int prot)511 static dma_addr_t __iommu_dma_map(struct device *dev, phys_addr_t phys,
512 		size_t size, int prot)
513 {
514 	struct iommu_domain *domain = iommu_get_dma_domain(dev);
515 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
516 	struct iova_domain *iovad = &cookie->iovad;
517 	size_t iova_off = iova_offset(iovad, phys);
518 	dma_addr_t iova;
519 
520 	size = iova_align(iovad, size + iova_off);
521 
522 	iova = iommu_dma_alloc_iova(domain, size, dma_get_mask(dev), dev);
523 	if (!iova)
524 		return DMA_MAPPING_ERROR;
525 
526 	if (iommu_map(domain, iova, phys - iova_off, size, prot)) {
527 		iommu_dma_free_iova(cookie, iova, size);
528 		return DMA_MAPPING_ERROR;
529 	}
530 	return iova + iova_off;
531 }
532 
__iommu_dma_free_pages(struct page ** pages,int count)533 static void __iommu_dma_free_pages(struct page **pages, int count)
534 {
535 	while (count--)
536 		__free_page(pages[count]);
537 	kvfree(pages);
538 }
539 
__iommu_dma_alloc_pages(struct device * dev,unsigned int count,unsigned long order_mask,gfp_t gfp)540 static struct page **__iommu_dma_alloc_pages(struct device *dev,
541 		unsigned int count, unsigned long order_mask, gfp_t gfp)
542 {
543 	struct page **pages;
544 	unsigned int i = 0, nid = dev_to_node(dev);
545 
546 	order_mask &= (2U << MAX_ORDER) - 1;
547 	if (!order_mask)
548 		return NULL;
549 
550 	pages = kvzalloc(count * sizeof(*pages), GFP_KERNEL);
551 	if (!pages)
552 		return NULL;
553 
554 	/* IOMMU can map any pages, so himem can also be used here */
555 	gfp |= __GFP_NOWARN | __GFP_HIGHMEM;
556 
557 	while (count) {
558 		struct page *page = NULL;
559 		unsigned int order_size;
560 
561 		/*
562 		 * Higher-order allocations are a convenience rather
563 		 * than a necessity, hence using __GFP_NORETRY until
564 		 * falling back to minimum-order allocations.
565 		 */
566 		for (order_mask &= (2U << __fls(count)) - 1;
567 		     order_mask; order_mask &= ~order_size) {
568 			unsigned int order = __fls(order_mask);
569 			gfp_t alloc_flags = gfp;
570 
571 			order_size = 1U << order;
572 			if (order_mask > order_size)
573 				alloc_flags |= __GFP_NORETRY;
574 			page = alloc_pages_node(nid, alloc_flags, order);
575 			if (!page)
576 				continue;
577 			if (!order)
578 				break;
579 			if (!PageCompound(page)) {
580 				split_page(page, order);
581 				break;
582 			} else if (!split_huge_page(page)) {
583 				break;
584 			}
585 			__free_pages(page, order);
586 		}
587 		if (!page) {
588 			__iommu_dma_free_pages(pages, i);
589 			return NULL;
590 		}
591 		count -= order_size;
592 		while (order_size--)
593 			pages[i++] = page++;
594 	}
595 	return pages;
596 }
597 
598 /**
599  * iommu_dma_alloc_remap - Allocate and map a buffer contiguous in IOVA space
600  * @dev: Device to allocate memory for. Must be a real device
601  *	 attached to an iommu_dma_domain
602  * @size: Size of buffer in bytes
603  * @dma_handle: Out argument for allocated DMA handle
604  * @gfp: Allocation flags
605  * @attrs: DMA attributes for this allocation
606  *
607  * If @size is less than PAGE_SIZE, then a full CPU page will be allocated,
608  * but an IOMMU which supports smaller pages might not map the whole thing.
609  *
610  * Return: Mapped virtual address, or NULL on failure.
611  */
iommu_dma_alloc_remap(struct device * dev,size_t size,dma_addr_t * dma_handle,gfp_t gfp,unsigned long attrs)612 static void *iommu_dma_alloc_remap(struct device *dev, size_t size,
613 		dma_addr_t *dma_handle, gfp_t gfp, unsigned long attrs)
614 {
615 	struct iommu_domain *domain = iommu_get_dma_domain(dev);
616 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
617 	struct iova_domain *iovad = &cookie->iovad;
618 	bool coherent = dev_is_dma_coherent(dev);
619 	int ioprot = dma_info_to_prot(DMA_BIDIRECTIONAL, coherent, attrs);
620 	pgprot_t prot = dma_pgprot(dev, PAGE_KERNEL, attrs);
621 	unsigned int count, min_size, alloc_sizes = domain->pgsize_bitmap;
622 	struct page **pages;
623 	struct sg_table sgt;
624 	dma_addr_t iova;
625 	void *vaddr;
626 
627 	*dma_handle = DMA_MAPPING_ERROR;
628 
629 	min_size = alloc_sizes & -alloc_sizes;
630 	if (min_size < PAGE_SIZE) {
631 		min_size = PAGE_SIZE;
632 		alloc_sizes |= PAGE_SIZE;
633 	} else {
634 		size = ALIGN(size, min_size);
635 	}
636 	if (attrs & DMA_ATTR_ALLOC_SINGLE_PAGES)
637 		alloc_sizes = min_size;
638 
639 	count = PAGE_ALIGN(size) >> PAGE_SHIFT;
640 	pages = __iommu_dma_alloc_pages(dev, count, alloc_sizes >> PAGE_SHIFT,
641 					gfp);
642 	if (!pages)
643 		return NULL;
644 
645 	size = iova_align(iovad, size);
646 	iova = iommu_dma_alloc_iova(domain, size, dev->coherent_dma_mask, dev);
647 	if (!iova)
648 		goto out_free_pages;
649 
650 	if (sg_alloc_table_from_pages(&sgt, pages, count, 0, size, GFP_KERNEL))
651 		goto out_free_iova;
652 
653 	if (!(ioprot & IOMMU_CACHE)) {
654 		struct scatterlist *sg;
655 		int i;
656 
657 		for_each_sg(sgt.sgl, sg, sgt.orig_nents, i)
658 			arch_dma_prep_coherent(sg_page(sg), sg->length);
659 	}
660 
661 	if (iommu_map_sg(domain, iova, sgt.sgl, sgt.orig_nents, ioprot)
662 			< size)
663 		goto out_free_sg;
664 
665 	vaddr = dma_common_pages_remap(pages, size, prot,
666 			__builtin_return_address(0));
667 	if (!vaddr)
668 		goto out_unmap;
669 
670 	*dma_handle = iova;
671 	sg_free_table(&sgt);
672 	return vaddr;
673 
674 out_unmap:
675 	__iommu_dma_unmap(dev, iova, size);
676 out_free_sg:
677 	sg_free_table(&sgt);
678 out_free_iova:
679 	iommu_dma_free_iova(cookie, iova, size);
680 out_free_pages:
681 	__iommu_dma_free_pages(pages, count);
682 	return NULL;
683 }
684 
685 /**
686  * __iommu_dma_mmap - Map a buffer into provided user VMA
687  * @pages: Array representing buffer from __iommu_dma_alloc()
688  * @size: Size of buffer in bytes
689  * @vma: VMA describing requested userspace mapping
690  *
691  * Maps the pages of the buffer in @pages into @vma. The caller is responsible
692  * for verifying the correct size and protection of @vma beforehand.
693  */
__iommu_dma_mmap(struct page ** pages,size_t size,struct vm_area_struct * vma)694 static int __iommu_dma_mmap(struct page **pages, size_t size,
695 		struct vm_area_struct *vma)
696 {
697 	return vm_map_pages(vma, pages, PAGE_ALIGN(size) >> PAGE_SHIFT);
698 }
699 
iommu_dma_sync_single_for_cpu(struct device * dev,dma_addr_t dma_handle,size_t size,enum dma_data_direction dir)700 static void iommu_dma_sync_single_for_cpu(struct device *dev,
701 		dma_addr_t dma_handle, size_t size, enum dma_data_direction dir)
702 {
703 	phys_addr_t phys;
704 
705 	if (dev_is_dma_coherent(dev))
706 		return;
707 
708 	phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle);
709 	arch_sync_dma_for_cpu(phys, size, dir);
710 }
711 
iommu_dma_sync_single_for_device(struct device * dev,dma_addr_t dma_handle,size_t size,enum dma_data_direction dir)712 static void iommu_dma_sync_single_for_device(struct device *dev,
713 		dma_addr_t dma_handle, size_t size, enum dma_data_direction dir)
714 {
715 	phys_addr_t phys;
716 
717 	if (dev_is_dma_coherent(dev))
718 		return;
719 
720 	phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle);
721 	arch_sync_dma_for_device(phys, size, dir);
722 }
723 
iommu_dma_sync_sg_for_cpu(struct device * dev,struct scatterlist * sgl,int nelems,enum dma_data_direction dir)724 static void iommu_dma_sync_sg_for_cpu(struct device *dev,
725 		struct scatterlist *sgl, int nelems,
726 		enum dma_data_direction dir)
727 {
728 	struct scatterlist *sg;
729 	int i;
730 
731 	if (dev_is_dma_coherent(dev))
732 		return;
733 
734 	for_each_sg(sgl, sg, nelems, i)
735 		arch_sync_dma_for_cpu(sg_phys(sg), sg->length, dir);
736 }
737 
iommu_dma_sync_sg_for_device(struct device * dev,struct scatterlist * sgl,int nelems,enum dma_data_direction dir)738 static void iommu_dma_sync_sg_for_device(struct device *dev,
739 		struct scatterlist *sgl, int nelems,
740 		enum dma_data_direction dir)
741 {
742 	struct scatterlist *sg;
743 	int i;
744 
745 	if (dev_is_dma_coherent(dev))
746 		return;
747 
748 	for_each_sg(sgl, sg, nelems, i)
749 		arch_sync_dma_for_device(sg_phys(sg), sg->length, dir);
750 }
751 
iommu_dma_map_page(struct device * dev,struct page * page,unsigned long offset,size_t size,enum dma_data_direction dir,unsigned long attrs)752 static dma_addr_t iommu_dma_map_page(struct device *dev, struct page *page,
753 		unsigned long offset, size_t size, enum dma_data_direction dir,
754 		unsigned long attrs)
755 {
756 	phys_addr_t phys = page_to_phys(page) + offset;
757 	bool coherent = dev_is_dma_coherent(dev);
758 	int prot = dma_info_to_prot(dir, coherent, attrs);
759 	dma_addr_t dma_handle;
760 
761 	dma_handle =__iommu_dma_map(dev, phys, size, prot);
762 	if (!coherent && !(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
763 	    dma_handle != DMA_MAPPING_ERROR)
764 		arch_sync_dma_for_device(phys, size, dir);
765 	return dma_handle;
766 }
767 
iommu_dma_unmap_page(struct device * dev,dma_addr_t dma_handle,size_t size,enum dma_data_direction dir,unsigned long attrs)768 static void iommu_dma_unmap_page(struct device *dev, dma_addr_t dma_handle,
769 		size_t size, enum dma_data_direction dir, unsigned long attrs)
770 {
771 	if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
772 		iommu_dma_sync_single_for_cpu(dev, dma_handle, size, dir);
773 	__iommu_dma_unmap(dev, dma_handle, size);
774 }
775 
776 /*
777  * Prepare a successfully-mapped scatterlist to give back to the caller.
778  *
779  * At this point the segments are already laid out by iommu_dma_map_sg() to
780  * avoid individually crossing any boundaries, so we merely need to check a
781  * segment's start address to avoid concatenating across one.
782  */
__finalise_sg(struct device * dev,struct scatterlist * sg,int nents,dma_addr_t dma_addr)783 static int __finalise_sg(struct device *dev, struct scatterlist *sg, int nents,
784 		dma_addr_t dma_addr)
785 {
786 	struct scatterlist *s, *cur = sg;
787 	unsigned long seg_mask = dma_get_seg_boundary(dev);
788 	unsigned int cur_len = 0, max_len = dma_get_max_seg_size(dev);
789 	int i, count = 0;
790 
791 	for_each_sg(sg, s, nents, i) {
792 		/* Restore this segment's original unaligned fields first */
793 		unsigned int s_iova_off = sg_dma_address(s);
794 		unsigned int s_length = sg_dma_len(s);
795 		unsigned int s_iova_len = s->length;
796 
797 		s->offset += s_iova_off;
798 		s->length = s_length;
799 		sg_dma_address(s) = DMA_MAPPING_ERROR;
800 		sg_dma_len(s) = 0;
801 
802 		/*
803 		 * Now fill in the real DMA data. If...
804 		 * - there is a valid output segment to append to
805 		 * - and this segment starts on an IOVA page boundary
806 		 * - but doesn't fall at a segment boundary
807 		 * - and wouldn't make the resulting output segment too long
808 		 */
809 		if (cur_len && !s_iova_off && (dma_addr & seg_mask) &&
810 		    (max_len - cur_len >= s_length)) {
811 			/* ...then concatenate it with the previous one */
812 			cur_len += s_length;
813 		} else {
814 			/* Otherwise start the next output segment */
815 			if (i > 0)
816 				cur = sg_next(cur);
817 			cur_len = s_length;
818 			count++;
819 
820 			sg_dma_address(cur) = dma_addr + s_iova_off;
821 		}
822 
823 		sg_dma_len(cur) = cur_len;
824 		dma_addr += s_iova_len;
825 
826 		if (s_length + s_iova_off < s_iova_len)
827 			cur_len = 0;
828 	}
829 	return count;
830 }
831 
832 /*
833  * If mapping failed, then just restore the original list,
834  * but making sure the DMA fields are invalidated.
835  */
__invalidate_sg(struct scatterlist * sg,int nents)836 static void __invalidate_sg(struct scatterlist *sg, int nents)
837 {
838 	struct scatterlist *s;
839 	int i;
840 
841 	for_each_sg(sg, s, nents, i) {
842 		if (sg_dma_address(s) != DMA_MAPPING_ERROR)
843 			s->offset += sg_dma_address(s);
844 		if (sg_dma_len(s))
845 			s->length = sg_dma_len(s);
846 		sg_dma_address(s) = DMA_MAPPING_ERROR;
847 		sg_dma_len(s) = 0;
848 	}
849 }
850 
851 /*
852  * The DMA API client is passing in a scatterlist which could describe
853  * any old buffer layout, but the IOMMU API requires everything to be
854  * aligned to IOMMU pages. Hence the need for this complicated bit of
855  * impedance-matching, to be able to hand off a suitably-aligned list,
856  * but still preserve the original offsets and sizes for the caller.
857  */
iommu_dma_map_sg(struct device * dev,struct scatterlist * sg,int nents,enum dma_data_direction dir,unsigned long attrs)858 static int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg,
859 		int nents, enum dma_data_direction dir, unsigned long attrs)
860 {
861 	struct iommu_domain *domain = iommu_get_dma_domain(dev);
862 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
863 	struct iova_domain *iovad = &cookie->iovad;
864 	struct scatterlist *s, *prev = NULL;
865 	int prot = dma_info_to_prot(dir, dev_is_dma_coherent(dev), attrs);
866 	dma_addr_t iova;
867 	size_t iova_len = 0;
868 	unsigned long mask = dma_get_seg_boundary(dev);
869 	int i;
870 
871 	if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
872 		iommu_dma_sync_sg_for_device(dev, sg, nents, dir);
873 
874 	/*
875 	 * Work out how much IOVA space we need, and align the segments to
876 	 * IOVA granules for the IOMMU driver to handle. With some clever
877 	 * trickery we can modify the list in-place, but reversibly, by
878 	 * stashing the unaligned parts in the as-yet-unused DMA fields.
879 	 */
880 	for_each_sg(sg, s, nents, i) {
881 		size_t s_iova_off = iova_offset(iovad, s->offset);
882 		size_t s_length = s->length;
883 		size_t pad_len = (mask - iova_len + 1) & mask;
884 
885 		sg_dma_address(s) = s_iova_off;
886 		sg_dma_len(s) = s_length;
887 		s->offset -= s_iova_off;
888 		s_length = iova_align(iovad, s_length + s_iova_off);
889 		s->length = s_length;
890 
891 		/*
892 		 * Due to the alignment of our single IOVA allocation, we can
893 		 * depend on these assumptions about the segment boundary mask:
894 		 * - If mask size >= IOVA size, then the IOVA range cannot
895 		 *   possibly fall across a boundary, so we don't care.
896 		 * - If mask size < IOVA size, then the IOVA range must start
897 		 *   exactly on a boundary, therefore we can lay things out
898 		 *   based purely on segment lengths without needing to know
899 		 *   the actual addresses beforehand.
900 		 * - The mask must be a power of 2, so pad_len == 0 if
901 		 *   iova_len == 0, thus we cannot dereference prev the first
902 		 *   time through here (i.e. before it has a meaningful value).
903 		 */
904 		if (pad_len && pad_len < s_length - 1) {
905 			prev->length += pad_len;
906 			iova_len += pad_len;
907 		}
908 
909 		iova_len += s_length;
910 		prev = s;
911 	}
912 
913 	iova = iommu_dma_alloc_iova(domain, iova_len, dma_get_mask(dev), dev);
914 	if (!iova)
915 		goto out_restore_sg;
916 
917 	/*
918 	 * We'll leave any physical concatenation to the IOMMU driver's
919 	 * implementation - it knows better than we do.
920 	 */
921 	if (iommu_map_sg(domain, iova, sg, nents, prot) < iova_len)
922 		goto out_free_iova;
923 
924 	return __finalise_sg(dev, sg, nents, iova);
925 
926 out_free_iova:
927 	iommu_dma_free_iova(cookie, iova, iova_len);
928 out_restore_sg:
929 	__invalidate_sg(sg, nents);
930 	return 0;
931 }
932 
iommu_dma_unmap_sg(struct device * dev,struct scatterlist * sg,int nents,enum dma_data_direction dir,unsigned long attrs)933 static void iommu_dma_unmap_sg(struct device *dev, struct scatterlist *sg,
934 		int nents, enum dma_data_direction dir, unsigned long attrs)
935 {
936 	dma_addr_t start, end;
937 	struct scatterlist *tmp;
938 	int i;
939 
940 	if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
941 		iommu_dma_sync_sg_for_cpu(dev, sg, nents, dir);
942 
943 	/*
944 	 * The scatterlist segments are mapped into a single
945 	 * contiguous IOVA allocation, so this is incredibly easy.
946 	 */
947 	start = sg_dma_address(sg);
948 	for_each_sg(sg_next(sg), tmp, nents - 1, i) {
949 		if (sg_dma_len(tmp) == 0)
950 			break;
951 		sg = tmp;
952 	}
953 	end = sg_dma_address(sg) + sg_dma_len(sg);
954 	__iommu_dma_unmap(dev, start, end - start);
955 }
956 
iommu_dma_map_resource(struct device * dev,phys_addr_t phys,size_t size,enum dma_data_direction dir,unsigned long attrs)957 static dma_addr_t iommu_dma_map_resource(struct device *dev, phys_addr_t phys,
958 		size_t size, enum dma_data_direction dir, unsigned long attrs)
959 {
960 	return __iommu_dma_map(dev, phys, size,
961 			dma_info_to_prot(dir, false, attrs) | IOMMU_MMIO);
962 }
963 
iommu_dma_unmap_resource(struct device * dev,dma_addr_t handle,size_t size,enum dma_data_direction dir,unsigned long attrs)964 static void iommu_dma_unmap_resource(struct device *dev, dma_addr_t handle,
965 		size_t size, enum dma_data_direction dir, unsigned long attrs)
966 {
967 	__iommu_dma_unmap(dev, handle, size);
968 }
969 
__iommu_dma_free(struct device * dev,size_t size,void * cpu_addr)970 static void __iommu_dma_free(struct device *dev, size_t size, void *cpu_addr)
971 {
972 	size_t alloc_size = PAGE_ALIGN(size);
973 	int count = alloc_size >> PAGE_SHIFT;
974 	struct page *page = NULL, **pages = NULL;
975 
976 	/* Non-coherent atomic allocation? Easy */
977 	if (IS_ENABLED(CONFIG_DMA_DIRECT_REMAP) &&
978 	    dma_free_from_pool(cpu_addr, alloc_size))
979 		return;
980 
981 	if (IS_ENABLED(CONFIG_DMA_REMAP) && is_vmalloc_addr(cpu_addr)) {
982 		/*
983 		 * If it the address is remapped, then it's either non-coherent
984 		 * or highmem CMA, or an iommu_dma_alloc_remap() construction.
985 		 */
986 		pages = dma_common_find_pages(cpu_addr);
987 		if (!pages)
988 			page = vmalloc_to_page(cpu_addr);
989 		dma_common_free_remap(cpu_addr, alloc_size);
990 	} else {
991 		/* Lowmem means a coherent atomic or CMA allocation */
992 		page = virt_to_page(cpu_addr);
993 	}
994 
995 	if (pages)
996 		__iommu_dma_free_pages(pages, count);
997 	if (page)
998 		dma_free_contiguous(dev, page, alloc_size);
999 }
1000 
iommu_dma_free(struct device * dev,size_t size,void * cpu_addr,dma_addr_t handle,unsigned long attrs)1001 static void iommu_dma_free(struct device *dev, size_t size, void *cpu_addr,
1002 		dma_addr_t handle, unsigned long attrs)
1003 {
1004 	__iommu_dma_unmap(dev, handle, size);
1005 	__iommu_dma_free(dev, size, cpu_addr);
1006 }
1007 
iommu_dma_alloc_pages(struct device * dev,size_t size,struct page ** pagep,gfp_t gfp,unsigned long attrs)1008 static void *iommu_dma_alloc_pages(struct device *dev, size_t size,
1009 		struct page **pagep, gfp_t gfp, unsigned long attrs)
1010 {
1011 	bool coherent = dev_is_dma_coherent(dev);
1012 	size_t alloc_size = PAGE_ALIGN(size);
1013 	int node = dev_to_node(dev);
1014 	struct page *page = NULL;
1015 	void *cpu_addr;
1016 
1017 	page = dma_alloc_contiguous(dev, alloc_size, gfp);
1018 	if (!page)
1019 		page = alloc_pages_node(node, gfp, get_order(alloc_size));
1020 	if (!page)
1021 		return NULL;
1022 
1023 	if (IS_ENABLED(CONFIG_DMA_REMAP) && (!coherent || PageHighMem(page))) {
1024 		pgprot_t prot = dma_pgprot(dev, PAGE_KERNEL, attrs);
1025 
1026 		cpu_addr = dma_common_contiguous_remap(page, alloc_size,
1027 				prot, __builtin_return_address(0));
1028 		if (!cpu_addr)
1029 			goto out_free_pages;
1030 
1031 		if (!coherent)
1032 			arch_dma_prep_coherent(page, size);
1033 	} else {
1034 		cpu_addr = page_address(page);
1035 	}
1036 
1037 	*pagep = page;
1038 	memset(cpu_addr, 0, alloc_size);
1039 	return cpu_addr;
1040 out_free_pages:
1041 	dma_free_contiguous(dev, page, alloc_size);
1042 	return NULL;
1043 }
1044 
iommu_dma_alloc(struct device * dev,size_t size,dma_addr_t * handle,gfp_t gfp,unsigned long attrs)1045 static void *iommu_dma_alloc(struct device *dev, size_t size,
1046 		dma_addr_t *handle, gfp_t gfp, unsigned long attrs)
1047 {
1048 	bool coherent = dev_is_dma_coherent(dev);
1049 	int ioprot = dma_info_to_prot(DMA_BIDIRECTIONAL, coherent, attrs);
1050 	struct page *page = NULL;
1051 	void *cpu_addr;
1052 
1053 	gfp |= __GFP_ZERO;
1054 
1055 	if (IS_ENABLED(CONFIG_DMA_REMAP) && gfpflags_allow_blocking(gfp) &&
1056 	    !(attrs & DMA_ATTR_FORCE_CONTIGUOUS))
1057 		return iommu_dma_alloc_remap(dev, size, handle, gfp, attrs);
1058 
1059 	if (IS_ENABLED(CONFIG_DMA_DIRECT_REMAP) &&
1060 	    !gfpflags_allow_blocking(gfp) && !coherent)
1061 		cpu_addr = dma_alloc_from_pool(PAGE_ALIGN(size), &page, gfp);
1062 	else
1063 		cpu_addr = iommu_dma_alloc_pages(dev, size, &page, gfp, attrs);
1064 	if (!cpu_addr)
1065 		return NULL;
1066 
1067 	*handle = __iommu_dma_map(dev, page_to_phys(page), size, ioprot);
1068 	if (*handle == DMA_MAPPING_ERROR) {
1069 		__iommu_dma_free(dev, size, cpu_addr);
1070 		return NULL;
1071 	}
1072 
1073 	return cpu_addr;
1074 }
1075 
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)1076 static int iommu_dma_mmap(struct device *dev, struct vm_area_struct *vma,
1077 		void *cpu_addr, dma_addr_t dma_addr, size_t size,
1078 		unsigned long attrs)
1079 {
1080 	unsigned long nr_pages = PAGE_ALIGN(size) >> PAGE_SHIFT;
1081 	unsigned long pfn, off = vma->vm_pgoff;
1082 	int ret;
1083 
1084 	vma->vm_page_prot = dma_pgprot(dev, vma->vm_page_prot, attrs);
1085 
1086 	if (dma_mmap_from_dev_coherent(dev, vma, cpu_addr, size, &ret))
1087 		return ret;
1088 
1089 	if (off >= nr_pages || vma_pages(vma) > nr_pages - off)
1090 		return -ENXIO;
1091 
1092 	if (IS_ENABLED(CONFIG_DMA_REMAP) && is_vmalloc_addr(cpu_addr)) {
1093 		struct page **pages = dma_common_find_pages(cpu_addr);
1094 
1095 		if (pages)
1096 			return __iommu_dma_mmap(pages, size, vma);
1097 		pfn = vmalloc_to_pfn(cpu_addr);
1098 	} else {
1099 		pfn = page_to_pfn(virt_to_page(cpu_addr));
1100 	}
1101 
1102 	return remap_pfn_range(vma, vma->vm_start, pfn + off,
1103 			       vma->vm_end - vma->vm_start,
1104 			       vma->vm_page_prot);
1105 }
1106 
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)1107 static int iommu_dma_get_sgtable(struct device *dev, struct sg_table *sgt,
1108 		void *cpu_addr, dma_addr_t dma_addr, size_t size,
1109 		unsigned long attrs)
1110 {
1111 	struct page *page;
1112 	int ret;
1113 
1114 	if (IS_ENABLED(CONFIG_DMA_REMAP) && is_vmalloc_addr(cpu_addr)) {
1115 		struct page **pages = dma_common_find_pages(cpu_addr);
1116 
1117 		if (pages) {
1118 			return sg_alloc_table_from_pages(sgt, pages,
1119 					PAGE_ALIGN(size) >> PAGE_SHIFT,
1120 					0, size, GFP_KERNEL);
1121 		}
1122 
1123 		page = vmalloc_to_page(cpu_addr);
1124 	} else {
1125 		page = virt_to_page(cpu_addr);
1126 	}
1127 
1128 	ret = sg_alloc_table(sgt, 1, GFP_KERNEL);
1129 	if (!ret)
1130 		sg_set_page(sgt->sgl, page, PAGE_ALIGN(size), 0);
1131 	return ret;
1132 }
1133 
iommu_dma_get_merge_boundary(struct device * dev)1134 static unsigned long iommu_dma_get_merge_boundary(struct device *dev)
1135 {
1136 	struct iommu_domain *domain = iommu_get_dma_domain(dev);
1137 
1138 	return (1UL << __ffs(domain->pgsize_bitmap)) - 1;
1139 }
1140 
1141 static const struct dma_map_ops iommu_dma_ops = {
1142 	.alloc			= iommu_dma_alloc,
1143 	.free			= iommu_dma_free,
1144 	.mmap			= iommu_dma_mmap,
1145 	.get_sgtable		= iommu_dma_get_sgtable,
1146 	.map_page		= iommu_dma_map_page,
1147 	.unmap_page		= iommu_dma_unmap_page,
1148 	.map_sg			= iommu_dma_map_sg,
1149 	.unmap_sg		= iommu_dma_unmap_sg,
1150 	.sync_single_for_cpu	= iommu_dma_sync_single_for_cpu,
1151 	.sync_single_for_device	= iommu_dma_sync_single_for_device,
1152 	.sync_sg_for_cpu	= iommu_dma_sync_sg_for_cpu,
1153 	.sync_sg_for_device	= iommu_dma_sync_sg_for_device,
1154 	.map_resource		= iommu_dma_map_resource,
1155 	.unmap_resource		= iommu_dma_unmap_resource,
1156 	.get_merge_boundary	= iommu_dma_get_merge_boundary,
1157 };
1158 
1159 /*
1160  * The IOMMU core code allocates the default DMA domain, which the underlying
1161  * IOMMU driver needs to support via the dma-iommu layer.
1162  */
iommu_setup_dma_ops(struct device * dev,u64 dma_base,u64 size)1163 void iommu_setup_dma_ops(struct device *dev, u64 dma_base, u64 size)
1164 {
1165 	struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
1166 
1167 	if (!domain)
1168 		goto out_err;
1169 
1170 	/*
1171 	 * The IOMMU core code allocates the default DMA domain, which the
1172 	 * underlying IOMMU driver needs to support via the dma-iommu layer.
1173 	 */
1174 	if (domain->type == IOMMU_DOMAIN_DMA) {
1175 		if (iommu_dma_init_domain(domain, dma_base, size, dev))
1176 			goto out_err;
1177 		dev->dma_ops = &iommu_dma_ops;
1178 	}
1179 
1180 	return;
1181 out_err:
1182 	 pr_warn("Failed to set up IOMMU for device %s; retaining platform DMA ops\n",
1183 		 dev_name(dev));
1184 }
1185 
iommu_dma_get_msi_page(struct device * dev,phys_addr_t msi_addr,struct iommu_domain * domain)1186 static struct iommu_dma_msi_page *iommu_dma_get_msi_page(struct device *dev,
1187 		phys_addr_t msi_addr, struct iommu_domain *domain)
1188 {
1189 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
1190 	struct iommu_dma_msi_page *msi_page;
1191 	dma_addr_t iova;
1192 	int prot = IOMMU_WRITE | IOMMU_NOEXEC | IOMMU_MMIO;
1193 	size_t size = cookie_msi_granule(cookie);
1194 
1195 	msi_addr &= ~(phys_addr_t)(size - 1);
1196 	list_for_each_entry(msi_page, &cookie->msi_page_list, list)
1197 		if (msi_page->phys == msi_addr)
1198 			return msi_page;
1199 
1200 	msi_page = kzalloc(sizeof(*msi_page), GFP_KERNEL);
1201 	if (!msi_page)
1202 		return NULL;
1203 
1204 	iova = iommu_dma_alloc_iova(domain, size, dma_get_mask(dev), dev);
1205 	if (!iova)
1206 		goto out_free_page;
1207 
1208 	if (iommu_map(domain, iova, msi_addr, size, prot))
1209 		goto out_free_iova;
1210 
1211 	INIT_LIST_HEAD(&msi_page->list);
1212 	msi_page->phys = msi_addr;
1213 	msi_page->iova = iova;
1214 	list_add(&msi_page->list, &cookie->msi_page_list);
1215 	return msi_page;
1216 
1217 out_free_iova:
1218 	iommu_dma_free_iova(cookie, iova, size);
1219 out_free_page:
1220 	kfree(msi_page);
1221 	return NULL;
1222 }
1223 
iommu_dma_prepare_msi(struct msi_desc * desc,phys_addr_t msi_addr)1224 int iommu_dma_prepare_msi(struct msi_desc *desc, phys_addr_t msi_addr)
1225 {
1226 	struct device *dev = msi_desc_to_dev(desc);
1227 	struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
1228 	struct iommu_dma_msi_page *msi_page;
1229 	static DEFINE_MUTEX(msi_prepare_lock); /* see below */
1230 
1231 	if (!domain || !domain->iova_cookie) {
1232 		desc->iommu_cookie = NULL;
1233 		return 0;
1234 	}
1235 
1236 	/*
1237 	 * In fact the whole prepare operation should already be serialised by
1238 	 * irq_domain_mutex further up the callchain, but that's pretty subtle
1239 	 * on its own, so consider this locking as failsafe documentation...
1240 	 */
1241 	mutex_lock(&msi_prepare_lock);
1242 	msi_page = iommu_dma_get_msi_page(dev, msi_addr, domain);
1243 	mutex_unlock(&msi_prepare_lock);
1244 
1245 	msi_desc_set_iommu_cookie(desc, msi_page);
1246 
1247 	if (!msi_page)
1248 		return -ENOMEM;
1249 	return 0;
1250 }
1251 
iommu_dma_compose_msi_msg(struct msi_desc * desc,struct msi_msg * msg)1252 void iommu_dma_compose_msi_msg(struct msi_desc *desc,
1253 			       struct msi_msg *msg)
1254 {
1255 	struct device *dev = msi_desc_to_dev(desc);
1256 	const struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
1257 	const struct iommu_dma_msi_page *msi_page;
1258 
1259 	msi_page = msi_desc_get_iommu_cookie(desc);
1260 
1261 	if (!domain || !domain->iova_cookie || WARN_ON(!msi_page))
1262 		return;
1263 
1264 	msg->address_hi = upper_32_bits(msi_page->iova);
1265 	msg->address_lo &= cookie_msi_granule(domain->iova_cookie) - 1;
1266 	msg->address_lo += lower_32_bits(msi_page->iova);
1267 }
1268 
iommu_dma_init(void)1269 static int iommu_dma_init(void)
1270 {
1271 	return iova_cache_get();
1272 }
1273 arch_initcall(iommu_dma_init);
1274