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