1 /*
2 * A fairly generic DMA-API to IOMMU-API glue layer.
3 *
4 * Copyright (C) 2014-2015 ARM Ltd.
5 *
6 * based in part on arch/arm/mm/dma-mapping.c:
7 * Copyright (C) 2000-2004 Russell King
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include <linux/device.h>
23 #include <linux/dma-iommu.h>
24 #include <linux/gfp.h>
25 #include <linux/huge_mm.h>
26 #include <linux/iommu.h>
27 #include <linux/iova.h>
28 #include <linux/mm.h>
29 #include <linux/scatterlist.h>
30 #include <linux/vmalloc.h>
31
iommu_dma_init(void)32 int iommu_dma_init(void)
33 {
34 return iova_cache_get();
35 }
36
37 /**
38 * iommu_get_dma_cookie - Acquire DMA-API resources for a domain
39 * @domain: IOMMU domain to prepare for DMA-API usage
40 *
41 * IOMMU drivers should normally call this from their domain_alloc
42 * callback when domain->type == IOMMU_DOMAIN_DMA.
43 */
iommu_get_dma_cookie(struct iommu_domain * domain)44 int iommu_get_dma_cookie(struct iommu_domain *domain)
45 {
46 struct iova_domain *iovad;
47
48 if (domain->iova_cookie)
49 return -EEXIST;
50
51 iovad = kzalloc(sizeof(*iovad), GFP_KERNEL);
52 domain->iova_cookie = iovad;
53
54 return iovad ? 0 : -ENOMEM;
55 }
56 EXPORT_SYMBOL(iommu_get_dma_cookie);
57
58 /**
59 * iommu_put_dma_cookie - Release a domain's DMA mapping resources
60 * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie()
61 *
62 * IOMMU drivers should normally call this from their domain_free callback.
63 */
iommu_put_dma_cookie(struct iommu_domain * domain)64 void iommu_put_dma_cookie(struct iommu_domain *domain)
65 {
66 struct iova_domain *iovad = domain->iova_cookie;
67
68 if (!iovad)
69 return;
70
71 if (iovad->granule)
72 put_iova_domain(iovad);
73 kfree(iovad);
74 domain->iova_cookie = NULL;
75 }
76 EXPORT_SYMBOL(iommu_put_dma_cookie);
77
78 /**
79 * iommu_dma_init_domain - Initialise a DMA mapping domain
80 * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie()
81 * @base: IOVA at which the mappable address space starts
82 * @size: Size of IOVA space
83 *
84 * @base and @size should be exact multiples of IOMMU page granularity to
85 * avoid rounding surprises. If necessary, we reserve the page at address 0
86 * to ensure it is an invalid IOVA. It is safe to reinitialise a domain, but
87 * any change which could make prior IOVAs invalid will fail.
88 */
iommu_dma_init_domain(struct iommu_domain * domain,dma_addr_t base,u64 size)89 int iommu_dma_init_domain(struct iommu_domain *domain, dma_addr_t base, u64 size)
90 {
91 struct iova_domain *iovad = domain->iova_cookie;
92 unsigned long order, base_pfn, end_pfn;
93
94 if (!iovad)
95 return -ENODEV;
96
97 /* Use the smallest supported page size for IOVA granularity */
98 order = __ffs(domain->ops->pgsize_bitmap);
99 base_pfn = max_t(unsigned long, 1, base >> order);
100 end_pfn = (base + size - 1) >> order;
101
102 /* Check the domain allows at least some access to the device... */
103 if (domain->geometry.force_aperture) {
104 if (base > domain->geometry.aperture_end ||
105 base + size <= domain->geometry.aperture_start) {
106 pr_warn("specified DMA range outside IOMMU capability\n");
107 return -EFAULT;
108 }
109 /* ...then finally give it a kicking to make sure it fits */
110 base_pfn = max_t(unsigned long, base_pfn,
111 domain->geometry.aperture_start >> order);
112 end_pfn = min_t(unsigned long, end_pfn,
113 domain->geometry.aperture_end >> order);
114 }
115
116 /* All we can safely do with an existing domain is enlarge it */
117 if (iovad->start_pfn) {
118 if (1UL << order != iovad->granule ||
119 base_pfn != iovad->start_pfn ||
120 end_pfn < iovad->dma_32bit_pfn) {
121 pr_warn("Incompatible range for DMA domain\n");
122 return -EFAULT;
123 }
124 iovad->dma_32bit_pfn = end_pfn;
125 } else {
126 init_iova_domain(iovad, 1UL << order, base_pfn, end_pfn);
127 }
128 return 0;
129 }
130 EXPORT_SYMBOL(iommu_dma_init_domain);
131
132 /**
133 * dma_direction_to_prot - Translate DMA API directions to IOMMU API page flags
134 * @dir: Direction of DMA transfer
135 * @coherent: Is the DMA master cache-coherent?
136 *
137 * Return: corresponding IOMMU API page protection flags
138 */
dma_direction_to_prot(enum dma_data_direction dir,bool coherent)139 int dma_direction_to_prot(enum dma_data_direction dir, bool coherent)
140 {
141 int prot = coherent ? IOMMU_CACHE : 0;
142
143 switch (dir) {
144 case DMA_BIDIRECTIONAL:
145 return prot | IOMMU_READ | IOMMU_WRITE;
146 case DMA_TO_DEVICE:
147 return prot | IOMMU_READ;
148 case DMA_FROM_DEVICE:
149 return prot | IOMMU_WRITE;
150 default:
151 return 0;
152 }
153 }
154
__alloc_iova(struct iommu_domain * domain,size_t size,dma_addr_t dma_limit)155 static struct iova *__alloc_iova(struct iommu_domain *domain, size_t size,
156 dma_addr_t dma_limit)
157 {
158 struct iova_domain *iovad = domain->iova_cookie;
159 unsigned long shift = iova_shift(iovad);
160 unsigned long length = iova_align(iovad, size) >> shift;
161
162 if (domain->geometry.force_aperture)
163 dma_limit = min(dma_limit, domain->geometry.aperture_end);
164 /*
165 * Enforce size-alignment to be safe - there could perhaps be an
166 * attribute to control this per-device, or at least per-domain...
167 */
168 return alloc_iova(iovad, length, dma_limit >> shift, true);
169 }
170
171 /* The IOVA allocator knows what we mapped, so just unmap whatever that was */
__iommu_dma_unmap(struct iommu_domain * domain,dma_addr_t dma_addr)172 static void __iommu_dma_unmap(struct iommu_domain *domain, dma_addr_t dma_addr)
173 {
174 struct iova_domain *iovad = domain->iova_cookie;
175 unsigned long shift = iova_shift(iovad);
176 unsigned long pfn = dma_addr >> shift;
177 struct iova *iova = find_iova(iovad, pfn);
178 size_t size;
179
180 if (WARN_ON(!iova))
181 return;
182
183 size = iova_size(iova) << shift;
184 size -= iommu_unmap(domain, pfn << shift, size);
185 /* ...and if we can't, then something is horribly, horribly wrong */
186 WARN_ON(size > 0);
187 __free_iova(iovad, iova);
188 }
189
__iommu_dma_free_pages(struct page ** pages,int count)190 static void __iommu_dma_free_pages(struct page **pages, int count)
191 {
192 while (count--)
193 __free_page(pages[count]);
194 kvfree(pages);
195 }
196
__iommu_dma_alloc_pages(unsigned int count,gfp_t gfp)197 static struct page **__iommu_dma_alloc_pages(unsigned int count, gfp_t gfp)
198 {
199 struct page **pages;
200 unsigned int i = 0, array_size = count * sizeof(*pages);
201 unsigned int order = MAX_ORDER;
202
203 if (array_size <= PAGE_SIZE)
204 pages = kzalloc(array_size, GFP_KERNEL);
205 else
206 pages = vzalloc(array_size);
207 if (!pages)
208 return NULL;
209
210 /* IOMMU can map any pages, so himem can also be used here */
211 gfp |= __GFP_NOWARN | __GFP_HIGHMEM;
212
213 while (count) {
214 struct page *page = NULL;
215 int j;
216
217 /*
218 * Higher-order allocations are a convenience rather
219 * than a necessity, hence using __GFP_NORETRY until
220 * falling back to single-page allocations.
221 */
222 for (order = min_t(unsigned int, order, __fls(count));
223 order > 0; order--) {
224 page = alloc_pages(gfp | __GFP_NORETRY, order);
225 if (!page)
226 continue;
227 if (PageCompound(page)) {
228 if (!split_huge_page(page))
229 break;
230 __free_pages(page, order);
231 } else {
232 split_page(page, order);
233 break;
234 }
235 }
236 if (!page)
237 page = alloc_page(gfp);
238 if (!page) {
239 __iommu_dma_free_pages(pages, i);
240 return NULL;
241 }
242 j = 1 << order;
243 count -= j;
244 while (j--)
245 pages[i++] = page++;
246 }
247 return pages;
248 }
249
250 /**
251 * iommu_dma_free - Free a buffer allocated by iommu_dma_alloc()
252 * @dev: Device which owns this buffer
253 * @pages: Array of buffer pages as returned by iommu_dma_alloc()
254 * @size: Size of buffer in bytes
255 * @handle: DMA address of buffer
256 *
257 * Frees both the pages associated with the buffer, and the array
258 * describing them
259 */
iommu_dma_free(struct device * dev,struct page ** pages,size_t size,dma_addr_t * handle)260 void iommu_dma_free(struct device *dev, struct page **pages, size_t size,
261 dma_addr_t *handle)
262 {
263 __iommu_dma_unmap(iommu_get_domain_for_dev(dev), *handle);
264 __iommu_dma_free_pages(pages, PAGE_ALIGN(size) >> PAGE_SHIFT);
265 *handle = DMA_ERROR_CODE;
266 }
267
268 /**
269 * iommu_dma_alloc - Allocate and map a buffer contiguous in IOVA space
270 * @dev: Device to allocate memory for. Must be a real device
271 * attached to an iommu_dma_domain
272 * @size: Size of buffer in bytes
273 * @gfp: Allocation flags
274 * @prot: IOMMU mapping flags
275 * @handle: Out argument for allocated DMA handle
276 * @flush_page: Arch callback which must ensure PAGE_SIZE bytes from the
277 * given VA/PA are visible to the given non-coherent device.
278 *
279 * If @size is less than PAGE_SIZE, then a full CPU page will be allocated,
280 * but an IOMMU which supports smaller pages might not map the whole thing.
281 *
282 * Return: Array of struct page pointers describing the buffer,
283 * or NULL on failure.
284 */
iommu_dma_alloc(struct device * dev,size_t size,gfp_t gfp,int prot,dma_addr_t * handle,void (* flush_page)(struct device *,const void *,phys_addr_t))285 struct page **iommu_dma_alloc(struct device *dev, size_t size,
286 gfp_t gfp, int prot, dma_addr_t *handle,
287 void (*flush_page)(struct device *, const void *, phys_addr_t))
288 {
289 struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
290 struct iova_domain *iovad = domain->iova_cookie;
291 struct iova *iova;
292 struct page **pages;
293 struct sg_table sgt;
294 dma_addr_t dma_addr;
295 unsigned int count = PAGE_ALIGN(size) >> PAGE_SHIFT;
296
297 *handle = DMA_ERROR_CODE;
298
299 pages = __iommu_dma_alloc_pages(count, gfp);
300 if (!pages)
301 return NULL;
302
303 iova = __alloc_iova(domain, size, dev->coherent_dma_mask);
304 if (!iova)
305 goto out_free_pages;
306
307 size = iova_align(iovad, size);
308 if (sg_alloc_table_from_pages(&sgt, pages, count, 0, size, GFP_KERNEL))
309 goto out_free_iova;
310
311 if (!(prot & IOMMU_CACHE)) {
312 struct sg_mapping_iter miter;
313 /*
314 * The CPU-centric flushing implied by SG_MITER_TO_SG isn't
315 * sufficient here, so skip it by using the "wrong" direction.
316 */
317 sg_miter_start(&miter, sgt.sgl, sgt.orig_nents, SG_MITER_FROM_SG);
318 while (sg_miter_next(&miter))
319 flush_page(dev, miter.addr, page_to_phys(miter.page));
320 sg_miter_stop(&miter);
321 }
322
323 dma_addr = iova_dma_addr(iovad, iova);
324 if (iommu_map_sg(domain, dma_addr, sgt.sgl, sgt.orig_nents, prot)
325 < size)
326 goto out_free_sg;
327
328 *handle = dma_addr;
329 sg_free_table(&sgt);
330 return pages;
331
332 out_free_sg:
333 sg_free_table(&sgt);
334 out_free_iova:
335 __free_iova(iovad, iova);
336 out_free_pages:
337 __iommu_dma_free_pages(pages, count);
338 return NULL;
339 }
340
341 /**
342 * iommu_dma_mmap - Map a buffer into provided user VMA
343 * @pages: Array representing buffer from iommu_dma_alloc()
344 * @size: Size of buffer in bytes
345 * @vma: VMA describing requested userspace mapping
346 *
347 * Maps the pages of the buffer in @pages into @vma. The caller is responsible
348 * for verifying the correct size and protection of @vma beforehand.
349 */
350
iommu_dma_mmap(struct page ** pages,size_t size,struct vm_area_struct * vma)351 int iommu_dma_mmap(struct page **pages, size_t size, struct vm_area_struct *vma)
352 {
353 unsigned long uaddr = vma->vm_start;
354 unsigned int i, count = PAGE_ALIGN(size) >> PAGE_SHIFT;
355 int ret = -ENXIO;
356
357 for (i = vma->vm_pgoff; i < count && uaddr < vma->vm_end; i++) {
358 ret = vm_insert_page(vma, uaddr, pages[i]);
359 if (ret)
360 break;
361 uaddr += PAGE_SIZE;
362 }
363 return ret;
364 }
365
iommu_dma_map_page(struct device * dev,struct page * page,unsigned long offset,size_t size,int prot)366 dma_addr_t iommu_dma_map_page(struct device *dev, struct page *page,
367 unsigned long offset, size_t size, int prot)
368 {
369 dma_addr_t dma_addr;
370 struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
371 struct iova_domain *iovad = domain->iova_cookie;
372 phys_addr_t phys = page_to_phys(page) + offset;
373 size_t iova_off = iova_offset(iovad, phys);
374 size_t len = iova_align(iovad, size + iova_off);
375 struct iova *iova = __alloc_iova(domain, len, dma_get_mask(dev));
376
377 if (!iova)
378 return DMA_ERROR_CODE;
379
380 dma_addr = iova_dma_addr(iovad, iova);
381 if (iommu_map(domain, dma_addr, phys - iova_off, len, prot)) {
382 __free_iova(iovad, iova);
383 return DMA_ERROR_CODE;
384 }
385 return dma_addr + iova_off;
386 }
387
iommu_dma_unmap_page(struct device * dev,dma_addr_t handle,size_t size,enum dma_data_direction dir,struct dma_attrs * attrs)388 void iommu_dma_unmap_page(struct device *dev, dma_addr_t handle, size_t size,
389 enum dma_data_direction dir, struct dma_attrs *attrs)
390 {
391 __iommu_dma_unmap(iommu_get_domain_for_dev(dev), handle);
392 }
393
394 /*
395 * Prepare a successfully-mapped scatterlist to give back to the caller.
396 * Handling IOVA concatenation can come later, if needed
397 */
__finalise_sg(struct device * dev,struct scatterlist * sg,int nents,dma_addr_t dma_addr)398 static int __finalise_sg(struct device *dev, struct scatterlist *sg, int nents,
399 dma_addr_t dma_addr)
400 {
401 struct scatterlist *s;
402 int i;
403
404 for_each_sg(sg, s, nents, i) {
405 /* Un-swizzling the fields here, hence the naming mismatch */
406 unsigned int s_offset = sg_dma_address(s);
407 unsigned int s_length = sg_dma_len(s);
408 unsigned int s_dma_len = s->length;
409
410 s->offset += s_offset;
411 s->length = s_length;
412 sg_dma_address(s) = dma_addr + s_offset;
413 dma_addr += s_dma_len;
414 }
415 return i;
416 }
417
418 /*
419 * If mapping failed, then just restore the original list,
420 * but making sure the DMA fields are invalidated.
421 */
__invalidate_sg(struct scatterlist * sg,int nents)422 static void __invalidate_sg(struct scatterlist *sg, int nents)
423 {
424 struct scatterlist *s;
425 int i;
426
427 for_each_sg(sg, s, nents, i) {
428 if (sg_dma_address(s) != DMA_ERROR_CODE)
429 s->offset += sg_dma_address(s);
430 if (sg_dma_len(s))
431 s->length = sg_dma_len(s);
432 sg_dma_address(s) = DMA_ERROR_CODE;
433 sg_dma_len(s) = 0;
434 }
435 }
436
437 /*
438 * The DMA API client is passing in a scatterlist which could describe
439 * any old buffer layout, but the IOMMU API requires everything to be
440 * aligned to IOMMU pages. Hence the need for this complicated bit of
441 * impedance-matching, to be able to hand off a suitably-aligned list,
442 * but still preserve the original offsets and sizes for the caller.
443 */
iommu_dma_map_sg(struct device * dev,struct scatterlist * sg,int nents,int prot)444 int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg,
445 int nents, int prot)
446 {
447 struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
448 struct iova_domain *iovad = domain->iova_cookie;
449 struct iova *iova;
450 struct scatterlist *s, *prev = NULL;
451 dma_addr_t dma_addr;
452 size_t iova_len = 0;
453 int i;
454
455 /*
456 * Work out how much IOVA space we need, and align the segments to
457 * IOVA granules for the IOMMU driver to handle. With some clever
458 * trickery we can modify the list in-place, but reversibly, by
459 * hiding the original data in the as-yet-unused DMA fields.
460 */
461 for_each_sg(sg, s, nents, i) {
462 size_t s_offset = iova_offset(iovad, s->offset);
463 size_t s_length = s->length;
464
465 sg_dma_address(s) = s_offset;
466 sg_dma_len(s) = s_length;
467 s->offset -= s_offset;
468 s_length = iova_align(iovad, s_length + s_offset);
469 s->length = s_length;
470
471 /*
472 * The simple way to avoid the rare case of a segment
473 * crossing the boundary mask is to pad the previous one
474 * to end at a naturally-aligned IOVA for this one's size,
475 * at the cost of potentially over-allocating a little.
476 */
477 if (prev) {
478 size_t pad_len = roundup_pow_of_two(s_length);
479
480 pad_len = (pad_len - iova_len) & (pad_len - 1);
481 prev->length += pad_len;
482 iova_len += pad_len;
483 }
484
485 iova_len += s_length;
486 prev = s;
487 }
488
489 iova = __alloc_iova(domain, iova_len, dma_get_mask(dev));
490 if (!iova)
491 goto out_restore_sg;
492
493 /*
494 * We'll leave any physical concatenation to the IOMMU driver's
495 * implementation - it knows better than we do.
496 */
497 dma_addr = iova_dma_addr(iovad, iova);
498 if (iommu_map_sg(domain, dma_addr, sg, nents, prot) < iova_len)
499 goto out_free_iova;
500
501 return __finalise_sg(dev, sg, nents, dma_addr);
502
503 out_free_iova:
504 __free_iova(iovad, iova);
505 out_restore_sg:
506 __invalidate_sg(sg, nents);
507 return 0;
508 }
509
iommu_dma_unmap_sg(struct device * dev,struct scatterlist * sg,int nents,enum dma_data_direction dir,struct dma_attrs * attrs)510 void iommu_dma_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
511 enum dma_data_direction dir, struct dma_attrs *attrs)
512 {
513 /*
514 * The scatterlist segments are mapped into a single
515 * contiguous IOVA allocation, so this is incredibly easy.
516 */
517 __iommu_dma_unmap(iommu_get_domain_for_dev(dev), sg_dma_address(sg));
518 }
519
iommu_dma_supported(struct device * dev,u64 mask)520 int iommu_dma_supported(struct device *dev, u64 mask)
521 {
522 /*
523 * 'Special' IOMMUs which don't have the same addressing capability
524 * as the CPU will have to wait until we have some way to query that
525 * before they'll be able to use this framework.
526 */
527 return 1;
528 }
529
iommu_dma_mapping_error(struct device * dev,dma_addr_t dma_addr)530 int iommu_dma_mapping_error(struct device *dev, dma_addr_t dma_addr)
531 {
532 return dma_addr == DMA_ERROR_CODE;
533 }
534