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