blob: 886cb3a7832629914c527d7645aa236b8a21e22a [file] [log] [blame]
Robin Murphy0db2e5d2015-10-01 20:13:58 +01001/*
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>
Robin Murphy5b11e9c2015-12-18 17:01:46 +000024#include <linux/gfp.h>
Robin Murphy0db2e5d2015-10-01 20:13:58 +010025#include <linux/huge_mm.h>
26#include <linux/iommu.h>
27#include <linux/iova.h>
28#include <linux/mm.h>
Robin Murphy5b11e9c2015-12-18 17:01:46 +000029#include <linux/scatterlist.h>
30#include <linux/vmalloc.h>
Robin Murphy0db2e5d2015-10-01 20:13:58 +010031
32int 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 */
44int 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}
56EXPORT_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 */
64void 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 put_iova_domain(iovad);
72 kfree(iovad);
73 domain->iova_cookie = NULL;
74}
75EXPORT_SYMBOL(iommu_put_dma_cookie);
76
77/**
78 * iommu_dma_init_domain - Initialise a DMA mapping domain
79 * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie()
80 * @base: IOVA at which the mappable address space starts
81 * @size: Size of IOVA space
82 *
83 * @base and @size should be exact multiples of IOMMU page granularity to
84 * avoid rounding surprises. If necessary, we reserve the page at address 0
85 * to ensure it is an invalid IOVA. It is safe to reinitialise a domain, but
86 * any change which could make prior IOVAs invalid will fail.
87 */
88int iommu_dma_init_domain(struct iommu_domain *domain, dma_addr_t base, u64 size)
89{
90 struct iova_domain *iovad = domain->iova_cookie;
91 unsigned long order, base_pfn, end_pfn;
92
93 if (!iovad)
94 return -ENODEV;
95
96 /* Use the smallest supported page size for IOVA granularity */
97 order = __ffs(domain->ops->pgsize_bitmap);
98 base_pfn = max_t(unsigned long, 1, base >> order);
99 end_pfn = (base + size - 1) >> order;
100
101 /* Check the domain allows at least some access to the device... */
102 if (domain->geometry.force_aperture) {
103 if (base > domain->geometry.aperture_end ||
104 base + size <= domain->geometry.aperture_start) {
105 pr_warn("specified DMA range outside IOMMU capability\n");
106 return -EFAULT;
107 }
108 /* ...then finally give it a kicking to make sure it fits */
109 base_pfn = max_t(unsigned long, base_pfn,
110 domain->geometry.aperture_start >> order);
111 end_pfn = min_t(unsigned long, end_pfn,
112 domain->geometry.aperture_end >> order);
113 }
114
115 /* All we can safely do with an existing domain is enlarge it */
116 if (iovad->start_pfn) {
117 if (1UL << order != iovad->granule ||
118 base_pfn != iovad->start_pfn ||
119 end_pfn < iovad->dma_32bit_pfn) {
120 pr_warn("Incompatible range for DMA domain\n");
121 return -EFAULT;
122 }
123 iovad->dma_32bit_pfn = end_pfn;
124 } else {
125 init_iova_domain(iovad, 1UL << order, base_pfn, end_pfn);
126 }
127 return 0;
128}
129EXPORT_SYMBOL(iommu_dma_init_domain);
130
131/**
132 * dma_direction_to_prot - Translate DMA API directions to IOMMU API page flags
133 * @dir: Direction of DMA transfer
134 * @coherent: Is the DMA master cache-coherent?
135 *
136 * Return: corresponding IOMMU API page protection flags
137 */
138int dma_direction_to_prot(enum dma_data_direction dir, bool coherent)
139{
140 int prot = coherent ? IOMMU_CACHE : 0;
141
142 switch (dir) {
143 case DMA_BIDIRECTIONAL:
144 return prot | IOMMU_READ | IOMMU_WRITE;
145 case DMA_TO_DEVICE:
146 return prot | IOMMU_READ;
147 case DMA_FROM_DEVICE:
148 return prot | IOMMU_WRITE;
149 default:
150 return 0;
151 }
152}
153
154static struct iova *__alloc_iova(struct iova_domain *iovad, size_t size,
155 dma_addr_t dma_limit)
156{
157 unsigned long shift = iova_shift(iovad);
158 unsigned long length = iova_align(iovad, size) >> shift;
159
160 /*
161 * Enforce size-alignment to be safe - there could perhaps be an
162 * attribute to control this per-device, or at least per-domain...
163 */
164 return alloc_iova(iovad, length, dma_limit >> shift, true);
165}
166
167/* The IOVA allocator knows what we mapped, so just unmap whatever that was */
168static void __iommu_dma_unmap(struct iommu_domain *domain, dma_addr_t dma_addr)
169{
170 struct iova_domain *iovad = domain->iova_cookie;
171 unsigned long shift = iova_shift(iovad);
172 unsigned long pfn = dma_addr >> shift;
173 struct iova *iova = find_iova(iovad, pfn);
174 size_t size;
175
176 if (WARN_ON(!iova))
177 return;
178
179 size = iova_size(iova) << shift;
180 size -= iommu_unmap(domain, pfn << shift, size);
181 /* ...and if we can't, then something is horribly, horribly wrong */
182 WARN_ON(size > 0);
183 __free_iova(iovad, iova);
184}
185
186static void __iommu_dma_free_pages(struct page **pages, int count)
187{
188 while (count--)
189 __free_page(pages[count]);
190 kvfree(pages);
191}
192
193static struct page **__iommu_dma_alloc_pages(unsigned int count, gfp_t gfp)
194{
195 struct page **pages;
196 unsigned int i = 0, array_size = count * sizeof(*pages);
Robin Murphy0a9afed2015-12-18 17:01:48 +0000197 unsigned int order = MAX_ORDER;
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100198
199 if (array_size <= PAGE_SIZE)
200 pages = kzalloc(array_size, GFP_KERNEL);
201 else
202 pages = vzalloc(array_size);
203 if (!pages)
204 return NULL;
205
206 /* IOMMU can map any pages, so himem can also be used here */
207 gfp |= __GFP_NOWARN | __GFP_HIGHMEM;
208
209 while (count) {
210 struct page *page = NULL;
Robin Murphy0a9afed2015-12-18 17:01:48 +0000211 int j;
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100212
213 /*
214 * Higher-order allocations are a convenience rather
215 * than a necessity, hence using __GFP_NORETRY until
216 * falling back to single-page allocations.
217 */
Robin Murphy0a9afed2015-12-18 17:01:48 +0000218 for (order = min_t(unsigned int, order, __fls(count));
219 order > 0; order--) {
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100220 page = alloc_pages(gfp | __GFP_NORETRY, order);
221 if (!page)
222 continue;
223 if (PageCompound(page)) {
224 if (!split_huge_page(page))
225 break;
226 __free_pages(page, order);
227 } else {
228 split_page(page, order);
229 break;
230 }
231 }
232 if (!page)
233 page = alloc_page(gfp);
234 if (!page) {
235 __iommu_dma_free_pages(pages, i);
236 return NULL;
237 }
238 j = 1 << order;
239 count -= j;
240 while (j--)
241 pages[i++] = page++;
242 }
243 return pages;
244}
245
246/**
247 * iommu_dma_free - Free a buffer allocated by iommu_dma_alloc()
248 * @dev: Device which owns this buffer
249 * @pages: Array of buffer pages as returned by iommu_dma_alloc()
250 * @size: Size of buffer in bytes
251 * @handle: DMA address of buffer
252 *
253 * Frees both the pages associated with the buffer, and the array
254 * describing them
255 */
256void iommu_dma_free(struct device *dev, struct page **pages, size_t size,
257 dma_addr_t *handle)
258{
259 __iommu_dma_unmap(iommu_get_domain_for_dev(dev), *handle);
260 __iommu_dma_free_pages(pages, PAGE_ALIGN(size) >> PAGE_SHIFT);
261 *handle = DMA_ERROR_CODE;
262}
263
264/**
265 * iommu_dma_alloc - Allocate and map a buffer contiguous in IOVA space
266 * @dev: Device to allocate memory for. Must be a real device
267 * attached to an iommu_dma_domain
268 * @size: Size of buffer in bytes
269 * @gfp: Allocation flags
270 * @prot: IOMMU mapping flags
271 * @handle: Out argument for allocated DMA handle
272 * @flush_page: Arch callback which must ensure PAGE_SIZE bytes from the
273 * given VA/PA are visible to the given non-coherent device.
274 *
275 * If @size is less than PAGE_SIZE, then a full CPU page will be allocated,
276 * but an IOMMU which supports smaller pages might not map the whole thing.
277 *
278 * Return: Array of struct page pointers describing the buffer,
279 * or NULL on failure.
280 */
281struct page **iommu_dma_alloc(struct device *dev, size_t size,
282 gfp_t gfp, int prot, dma_addr_t *handle,
283 void (*flush_page)(struct device *, const void *, phys_addr_t))
284{
285 struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
286 struct iova_domain *iovad = domain->iova_cookie;
287 struct iova *iova;
288 struct page **pages;
289 struct sg_table sgt;
290 dma_addr_t dma_addr;
291 unsigned int count = PAGE_ALIGN(size) >> PAGE_SHIFT;
292
293 *handle = DMA_ERROR_CODE;
294
295 pages = __iommu_dma_alloc_pages(count, gfp);
296 if (!pages)
297 return NULL;
298
299 iova = __alloc_iova(iovad, size, dev->coherent_dma_mask);
300 if (!iova)
301 goto out_free_pages;
302
303 size = iova_align(iovad, size);
304 if (sg_alloc_table_from_pages(&sgt, pages, count, 0, size, GFP_KERNEL))
305 goto out_free_iova;
306
307 if (!(prot & IOMMU_CACHE)) {
308 struct sg_mapping_iter miter;
309 /*
310 * The CPU-centric flushing implied by SG_MITER_TO_SG isn't
311 * sufficient here, so skip it by using the "wrong" direction.
312 */
313 sg_miter_start(&miter, sgt.sgl, sgt.orig_nents, SG_MITER_FROM_SG);
314 while (sg_miter_next(&miter))
315 flush_page(dev, miter.addr, page_to_phys(miter.page));
316 sg_miter_stop(&miter);
317 }
318
319 dma_addr = iova_dma_addr(iovad, iova);
320 if (iommu_map_sg(domain, dma_addr, sgt.sgl, sgt.orig_nents, prot)
321 < size)
322 goto out_free_sg;
323
324 *handle = dma_addr;
325 sg_free_table(&sgt);
326 return pages;
327
328out_free_sg:
329 sg_free_table(&sgt);
330out_free_iova:
331 __free_iova(iovad, iova);
332out_free_pages:
333 __iommu_dma_free_pages(pages, count);
334 return NULL;
335}
336
337/**
338 * iommu_dma_mmap - Map a buffer into provided user VMA
339 * @pages: Array representing buffer from iommu_dma_alloc()
340 * @size: Size of buffer in bytes
341 * @vma: VMA describing requested userspace mapping
342 *
343 * Maps the pages of the buffer in @pages into @vma. The caller is responsible
344 * for verifying the correct size and protection of @vma beforehand.
345 */
346
347int iommu_dma_mmap(struct page **pages, size_t size, struct vm_area_struct *vma)
348{
349 unsigned long uaddr = vma->vm_start;
350 unsigned int i, count = PAGE_ALIGN(size) >> PAGE_SHIFT;
351 int ret = -ENXIO;
352
353 for (i = vma->vm_pgoff; i < count && uaddr < vma->vm_end; i++) {
354 ret = vm_insert_page(vma, uaddr, pages[i]);
355 if (ret)
356 break;
357 uaddr += PAGE_SIZE;
358 }
359 return ret;
360}
361
362dma_addr_t iommu_dma_map_page(struct device *dev, struct page *page,
363 unsigned long offset, size_t size, int prot)
364{
365 dma_addr_t dma_addr;
366 struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
367 struct iova_domain *iovad = domain->iova_cookie;
368 phys_addr_t phys = page_to_phys(page) + offset;
369 size_t iova_off = iova_offset(iovad, phys);
370 size_t len = iova_align(iovad, size + iova_off);
371 struct iova *iova = __alloc_iova(iovad, len, dma_get_mask(dev));
372
373 if (!iova)
374 return DMA_ERROR_CODE;
375
376 dma_addr = iova_dma_addr(iovad, iova);
377 if (iommu_map(domain, dma_addr, phys - iova_off, len, prot)) {
378 __free_iova(iovad, iova);
379 return DMA_ERROR_CODE;
380 }
381 return dma_addr + iova_off;
382}
383
384void iommu_dma_unmap_page(struct device *dev, dma_addr_t handle, size_t size,
385 enum dma_data_direction dir, struct dma_attrs *attrs)
386{
387 __iommu_dma_unmap(iommu_get_domain_for_dev(dev), handle);
388}
389
390/*
391 * Prepare a successfully-mapped scatterlist to give back to the caller.
Robin Murphy809eac52016-04-11 12:32:31 +0100392 *
393 * At this point the segments are already laid out by iommu_dma_map_sg() to
394 * avoid individually crossing any boundaries, so we merely need to check a
395 * segment's start address to avoid concatenating across one.
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100396 */
397static int __finalise_sg(struct device *dev, struct scatterlist *sg, int nents,
398 dma_addr_t dma_addr)
399{
Robin Murphy809eac52016-04-11 12:32:31 +0100400 struct scatterlist *s, *cur = sg;
401 unsigned long seg_mask = dma_get_seg_boundary(dev);
402 unsigned int cur_len = 0, max_len = dma_get_max_seg_size(dev);
403 int i, count = 0;
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100404
405 for_each_sg(sg, s, nents, i) {
Robin Murphy809eac52016-04-11 12:32:31 +0100406 /* Restore this segment's original unaligned fields first */
407 unsigned int s_iova_off = sg_dma_address(s);
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100408 unsigned int s_length = sg_dma_len(s);
Robin Murphy809eac52016-04-11 12:32:31 +0100409 unsigned int s_iova_len = s->length;
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100410
Robin Murphy809eac52016-04-11 12:32:31 +0100411 s->offset += s_iova_off;
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100412 s->length = s_length;
Robin Murphy809eac52016-04-11 12:32:31 +0100413 sg_dma_address(s) = DMA_ERROR_CODE;
414 sg_dma_len(s) = 0;
415
416 /*
417 * Now fill in the real DMA data. If...
418 * - there is a valid output segment to append to
419 * - and this segment starts on an IOVA page boundary
420 * - but doesn't fall at a segment boundary
421 * - and wouldn't make the resulting output segment too long
422 */
423 if (cur_len && !s_iova_off && (dma_addr & seg_mask) &&
424 (cur_len + s_length <= max_len)) {
425 /* ...then concatenate it with the previous one */
426 cur_len += s_length;
427 } else {
428 /* Otherwise start the next output segment */
429 if (i > 0)
430 cur = sg_next(cur);
431 cur_len = s_length;
432 count++;
433
434 sg_dma_address(cur) = dma_addr + s_iova_off;
435 }
436
437 sg_dma_len(cur) = cur_len;
438 dma_addr += s_iova_len;
439
440 if (s_length + s_iova_off < s_iova_len)
441 cur_len = 0;
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100442 }
Robin Murphy809eac52016-04-11 12:32:31 +0100443 return count;
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100444}
445
446/*
447 * If mapping failed, then just restore the original list,
448 * but making sure the DMA fields are invalidated.
449 */
450static void __invalidate_sg(struct scatterlist *sg, int nents)
451{
452 struct scatterlist *s;
453 int i;
454
455 for_each_sg(sg, s, nents, i) {
456 if (sg_dma_address(s) != DMA_ERROR_CODE)
Robin Murphy07b48ac2016-03-10 19:28:12 +0000457 s->offset += sg_dma_address(s);
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100458 if (sg_dma_len(s))
459 s->length = sg_dma_len(s);
460 sg_dma_address(s) = DMA_ERROR_CODE;
461 sg_dma_len(s) = 0;
462 }
463}
464
465/*
466 * The DMA API client is passing in a scatterlist which could describe
467 * any old buffer layout, but the IOMMU API requires everything to be
468 * aligned to IOMMU pages. Hence the need for this complicated bit of
469 * impedance-matching, to be able to hand off a suitably-aligned list,
470 * but still preserve the original offsets and sizes for the caller.
471 */
472int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg,
473 int nents, int prot)
474{
475 struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
476 struct iova_domain *iovad = domain->iova_cookie;
477 struct iova *iova;
478 struct scatterlist *s, *prev = NULL;
479 dma_addr_t dma_addr;
480 size_t iova_len = 0;
Robin Murphy809eac52016-04-11 12:32:31 +0100481 unsigned long mask = dma_get_seg_boundary(dev);
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100482 int i;
483
484 /*
485 * Work out how much IOVA space we need, and align the segments to
486 * IOVA granules for the IOMMU driver to handle. With some clever
487 * trickery we can modify the list in-place, but reversibly, by
Robin Murphy809eac52016-04-11 12:32:31 +0100488 * stashing the unaligned parts in the as-yet-unused DMA fields.
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100489 */
490 for_each_sg(sg, s, nents, i) {
Robin Murphy809eac52016-04-11 12:32:31 +0100491 size_t s_iova_off = iova_offset(iovad, s->offset);
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100492 size_t s_length = s->length;
Robin Murphy809eac52016-04-11 12:32:31 +0100493 size_t pad_len = (mask - iova_len + 1) & mask;
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100494
Robin Murphy809eac52016-04-11 12:32:31 +0100495 sg_dma_address(s) = s_iova_off;
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100496 sg_dma_len(s) = s_length;
Robin Murphy809eac52016-04-11 12:32:31 +0100497 s->offset -= s_iova_off;
498 s_length = iova_align(iovad, s_length + s_iova_off);
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100499 s->length = s_length;
500
501 /*
Robin Murphy809eac52016-04-11 12:32:31 +0100502 * Due to the alignment of our single IOVA allocation, we can
503 * depend on these assumptions about the segment boundary mask:
504 * - If mask size >= IOVA size, then the IOVA range cannot
505 * possibly fall across a boundary, so we don't care.
506 * - If mask size < IOVA size, then the IOVA range must start
507 * exactly on a boundary, therefore we can lay things out
508 * based purely on segment lengths without needing to know
509 * the actual addresses beforehand.
510 * - The mask must be a power of 2, so pad_len == 0 if
511 * iova_len == 0, thus we cannot dereference prev the first
512 * time through here (i.e. before it has a meaningful value).
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100513 */
Robin Murphy809eac52016-04-11 12:32:31 +0100514 if (pad_len && pad_len < s_length - 1) {
Robin Murphy0db2e5d2015-10-01 20:13:58 +0100515 prev->length += pad_len;
516 iova_len += pad_len;
517 }
518
519 iova_len += s_length;
520 prev = s;
521 }
522
523 iova = __alloc_iova(iovad, iova_len, dma_get_mask(dev));
524 if (!iova)
525 goto out_restore_sg;
526
527 /*
528 * We'll leave any physical concatenation to the IOMMU driver's
529 * implementation - it knows better than we do.
530 */
531 dma_addr = iova_dma_addr(iovad, iova);
532 if (iommu_map_sg(domain, dma_addr, sg, nents, prot) < iova_len)
533 goto out_free_iova;
534
535 return __finalise_sg(dev, sg, nents, dma_addr);
536
537out_free_iova:
538 __free_iova(iovad, iova);
539out_restore_sg:
540 __invalidate_sg(sg, nents);
541 return 0;
542}
543
544void iommu_dma_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
545 enum dma_data_direction dir, struct dma_attrs *attrs)
546{
547 /*
548 * The scatterlist segments are mapped into a single
549 * contiguous IOVA allocation, so this is incredibly easy.
550 */
551 __iommu_dma_unmap(iommu_get_domain_for_dev(dev), sg_dma_address(sg));
552}
553
554int iommu_dma_supported(struct device *dev, u64 mask)
555{
556 /*
557 * 'Special' IOMMUs which don't have the same addressing capability
558 * as the CPU will have to wait until we have some way to query that
559 * before they'll be able to use this framework.
560 */
561 return 1;
562}
563
564int iommu_dma_mapping_error(struct device *dev, dma_addr_t dma_addr)
565{
566 return dma_addr == DMA_ERROR_CODE;
567}