xref: /openbmc/linux/arch/arm/mm/dma-mapping.c (revision 05bcf503)
1 /*
2  *  linux/arch/arm/mm/dma-mapping.c
3  *
4  *  Copyright (C) 2000-2004 Russell King
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  *
10  *  DMA uncached mapping support.
11  */
12 #include <linux/module.h>
13 #include <linux/mm.h>
14 #include <linux/gfp.h>
15 #include <linux/errno.h>
16 #include <linux/list.h>
17 #include <linux/init.h>
18 #include <linux/device.h>
19 #include <linux/dma-mapping.h>
20 #include <linux/dma-contiguous.h>
21 #include <linux/highmem.h>
22 #include <linux/memblock.h>
23 #include <linux/slab.h>
24 #include <linux/iommu.h>
25 #include <linux/io.h>
26 #include <linux/vmalloc.h>
27 #include <linux/sizes.h>
28 
29 #include <asm/memory.h>
30 #include <asm/highmem.h>
31 #include <asm/cacheflush.h>
32 #include <asm/tlbflush.h>
33 #include <asm/mach/arch.h>
34 #include <asm/dma-iommu.h>
35 #include <asm/mach/map.h>
36 #include <asm/system_info.h>
37 #include <asm/dma-contiguous.h>
38 
39 #include "mm.h"
40 
41 /*
42  * The DMA API is built upon the notion of "buffer ownership".  A buffer
43  * is either exclusively owned by the CPU (and therefore may be accessed
44  * by it) or exclusively owned by the DMA device.  These helper functions
45  * represent the transitions between these two ownership states.
46  *
47  * Note, however, that on later ARMs, this notion does not work due to
48  * speculative prefetches.  We model our approach on the assumption that
49  * the CPU does do speculative prefetches, which means we clean caches
50  * before transfers and delay cache invalidation until transfer completion.
51  *
52  */
53 static void __dma_page_cpu_to_dev(struct page *, unsigned long,
54 		size_t, enum dma_data_direction);
55 static void __dma_page_dev_to_cpu(struct page *, unsigned long,
56 		size_t, enum dma_data_direction);
57 
58 /**
59  * arm_dma_map_page - map a portion of a page for streaming DMA
60  * @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
61  * @page: page that buffer resides in
62  * @offset: offset into page for start of buffer
63  * @size: size of buffer to map
64  * @dir: DMA transfer direction
65  *
66  * Ensure that any data held in the cache is appropriately discarded
67  * or written back.
68  *
69  * The device owns this memory once this call has completed.  The CPU
70  * can regain ownership by calling dma_unmap_page().
71  */
72 static dma_addr_t arm_dma_map_page(struct device *dev, struct page *page,
73 	     unsigned long offset, size_t size, enum dma_data_direction dir,
74 	     struct dma_attrs *attrs)
75 {
76 	if (!dma_get_attr(DMA_ATTR_SKIP_CPU_SYNC, attrs))
77 		__dma_page_cpu_to_dev(page, offset, size, dir);
78 	return pfn_to_dma(dev, page_to_pfn(page)) + offset;
79 }
80 
81 static dma_addr_t arm_coherent_dma_map_page(struct device *dev, struct page *page,
82 	     unsigned long offset, size_t size, enum dma_data_direction dir,
83 	     struct dma_attrs *attrs)
84 {
85 	return pfn_to_dma(dev, page_to_pfn(page)) + offset;
86 }
87 
88 /**
89  * arm_dma_unmap_page - unmap a buffer previously mapped through dma_map_page()
90  * @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
91  * @handle: DMA address of buffer
92  * @size: size of buffer (same as passed to dma_map_page)
93  * @dir: DMA transfer direction (same as passed to dma_map_page)
94  *
95  * Unmap a page streaming mode DMA translation.  The handle and size
96  * must match what was provided in the previous dma_map_page() call.
97  * All other usages are undefined.
98  *
99  * After this call, reads by the CPU to the buffer are guaranteed to see
100  * whatever the device wrote there.
101  */
102 static void arm_dma_unmap_page(struct device *dev, dma_addr_t handle,
103 		size_t size, enum dma_data_direction dir,
104 		struct dma_attrs *attrs)
105 {
106 	if (!dma_get_attr(DMA_ATTR_SKIP_CPU_SYNC, attrs))
107 		__dma_page_dev_to_cpu(pfn_to_page(dma_to_pfn(dev, handle)),
108 				      handle & ~PAGE_MASK, size, dir);
109 }
110 
111 static void arm_dma_sync_single_for_cpu(struct device *dev,
112 		dma_addr_t handle, size_t size, enum dma_data_direction dir)
113 {
114 	unsigned int offset = handle & (PAGE_SIZE - 1);
115 	struct page *page = pfn_to_page(dma_to_pfn(dev, handle-offset));
116 	__dma_page_dev_to_cpu(page, offset, size, dir);
117 }
118 
119 static void arm_dma_sync_single_for_device(struct device *dev,
120 		dma_addr_t handle, size_t size, enum dma_data_direction dir)
121 {
122 	unsigned int offset = handle & (PAGE_SIZE - 1);
123 	struct page *page = pfn_to_page(dma_to_pfn(dev, handle-offset));
124 	__dma_page_cpu_to_dev(page, offset, size, dir);
125 }
126 
127 static int arm_dma_set_mask(struct device *dev, u64 dma_mask);
128 
129 struct dma_map_ops arm_dma_ops = {
130 	.alloc			= arm_dma_alloc,
131 	.free			= arm_dma_free,
132 	.mmap			= arm_dma_mmap,
133 	.get_sgtable		= arm_dma_get_sgtable,
134 	.map_page		= arm_dma_map_page,
135 	.unmap_page		= arm_dma_unmap_page,
136 	.map_sg			= arm_dma_map_sg,
137 	.unmap_sg		= arm_dma_unmap_sg,
138 	.sync_single_for_cpu	= arm_dma_sync_single_for_cpu,
139 	.sync_single_for_device	= arm_dma_sync_single_for_device,
140 	.sync_sg_for_cpu	= arm_dma_sync_sg_for_cpu,
141 	.sync_sg_for_device	= arm_dma_sync_sg_for_device,
142 	.set_dma_mask		= arm_dma_set_mask,
143 };
144 EXPORT_SYMBOL(arm_dma_ops);
145 
146 static void *arm_coherent_dma_alloc(struct device *dev, size_t size,
147 	dma_addr_t *handle, gfp_t gfp, struct dma_attrs *attrs);
148 static void arm_coherent_dma_free(struct device *dev, size_t size, void *cpu_addr,
149 				  dma_addr_t handle, struct dma_attrs *attrs);
150 
151 struct dma_map_ops arm_coherent_dma_ops = {
152 	.alloc			= arm_coherent_dma_alloc,
153 	.free			= arm_coherent_dma_free,
154 	.mmap			= arm_dma_mmap,
155 	.get_sgtable		= arm_dma_get_sgtable,
156 	.map_page		= arm_coherent_dma_map_page,
157 	.map_sg			= arm_dma_map_sg,
158 	.set_dma_mask		= arm_dma_set_mask,
159 };
160 EXPORT_SYMBOL(arm_coherent_dma_ops);
161 
162 static u64 get_coherent_dma_mask(struct device *dev)
163 {
164 	u64 mask = (u64)arm_dma_limit;
165 
166 	if (dev) {
167 		mask = dev->coherent_dma_mask;
168 
169 		/*
170 		 * Sanity check the DMA mask - it must be non-zero, and
171 		 * must be able to be satisfied by a DMA allocation.
172 		 */
173 		if (mask == 0) {
174 			dev_warn(dev, "coherent DMA mask is unset\n");
175 			return 0;
176 		}
177 
178 		if ((~mask) & (u64)arm_dma_limit) {
179 			dev_warn(dev, "coherent DMA mask %#llx is smaller "
180 				 "than system GFP_DMA mask %#llx\n",
181 				 mask, (u64)arm_dma_limit);
182 			return 0;
183 		}
184 	}
185 
186 	return mask;
187 }
188 
189 static void __dma_clear_buffer(struct page *page, size_t size)
190 {
191 	void *ptr;
192 	/*
193 	 * Ensure that the allocated pages are zeroed, and that any data
194 	 * lurking in the kernel direct-mapped region is invalidated.
195 	 */
196 	ptr = page_address(page);
197 	if (ptr) {
198 		memset(ptr, 0, size);
199 		dmac_flush_range(ptr, ptr + size);
200 		outer_flush_range(__pa(ptr), __pa(ptr) + size);
201 	}
202 }
203 
204 /*
205  * Allocate a DMA buffer for 'dev' of size 'size' using the
206  * specified gfp mask.  Note that 'size' must be page aligned.
207  */
208 static struct page *__dma_alloc_buffer(struct device *dev, size_t size, gfp_t gfp)
209 {
210 	unsigned long order = get_order(size);
211 	struct page *page, *p, *e;
212 
213 	page = alloc_pages(gfp, order);
214 	if (!page)
215 		return NULL;
216 
217 	/*
218 	 * Now split the huge page and free the excess pages
219 	 */
220 	split_page(page, order);
221 	for (p = page + (size >> PAGE_SHIFT), e = page + (1 << order); p < e; p++)
222 		__free_page(p);
223 
224 	__dma_clear_buffer(page, size);
225 
226 	return page;
227 }
228 
229 /*
230  * Free a DMA buffer.  'size' must be page aligned.
231  */
232 static void __dma_free_buffer(struct page *page, size_t size)
233 {
234 	struct page *e = page + (size >> PAGE_SHIFT);
235 
236 	while (page < e) {
237 		__free_page(page);
238 		page++;
239 	}
240 }
241 
242 #ifdef CONFIG_MMU
243 #ifdef CONFIG_HUGETLB_PAGE
244 #error ARM Coherent DMA allocator does not (yet) support huge TLB
245 #endif
246 
247 static void *__alloc_from_contiguous(struct device *dev, size_t size,
248 				     pgprot_t prot, struct page **ret_page);
249 
250 static void *__alloc_remap_buffer(struct device *dev, size_t size, gfp_t gfp,
251 				 pgprot_t prot, struct page **ret_page,
252 				 const void *caller);
253 
254 static void *
255 __dma_alloc_remap(struct page *page, size_t size, gfp_t gfp, pgprot_t prot,
256 	const void *caller)
257 {
258 	struct vm_struct *area;
259 	unsigned long addr;
260 
261 	/*
262 	 * DMA allocation can be mapped to user space, so lets
263 	 * set VM_USERMAP flags too.
264 	 */
265 	area = get_vm_area_caller(size, VM_ARM_DMA_CONSISTENT | VM_USERMAP,
266 				  caller);
267 	if (!area)
268 		return NULL;
269 	addr = (unsigned long)area->addr;
270 	area->phys_addr = __pfn_to_phys(page_to_pfn(page));
271 
272 	if (ioremap_page_range(addr, addr + size, area->phys_addr, prot)) {
273 		vunmap((void *)addr);
274 		return NULL;
275 	}
276 	return (void *)addr;
277 }
278 
279 static void __dma_free_remap(void *cpu_addr, size_t size)
280 {
281 	unsigned int flags = VM_ARM_DMA_CONSISTENT | VM_USERMAP;
282 	struct vm_struct *area = find_vm_area(cpu_addr);
283 	if (!area || (area->flags & flags) != flags) {
284 		WARN(1, "trying to free invalid coherent area: %p\n", cpu_addr);
285 		return;
286 	}
287 	unmap_kernel_range((unsigned long)cpu_addr, size);
288 	vunmap(cpu_addr);
289 }
290 
291 #define DEFAULT_DMA_COHERENT_POOL_SIZE	SZ_256K
292 
293 struct dma_pool {
294 	size_t size;
295 	spinlock_t lock;
296 	unsigned long *bitmap;
297 	unsigned long nr_pages;
298 	void *vaddr;
299 	struct page **pages;
300 };
301 
302 static struct dma_pool atomic_pool = {
303 	.size = DEFAULT_DMA_COHERENT_POOL_SIZE,
304 };
305 
306 static int __init early_coherent_pool(char *p)
307 {
308 	atomic_pool.size = memparse(p, &p);
309 	return 0;
310 }
311 early_param("coherent_pool", early_coherent_pool);
312 
313 void __init init_dma_coherent_pool_size(unsigned long size)
314 {
315 	/*
316 	 * Catch any attempt to set the pool size too late.
317 	 */
318 	BUG_ON(atomic_pool.vaddr);
319 
320 	/*
321 	 * Set architecture specific coherent pool size only if
322 	 * it has not been changed by kernel command line parameter.
323 	 */
324 	if (atomic_pool.size == DEFAULT_DMA_COHERENT_POOL_SIZE)
325 		atomic_pool.size = size;
326 }
327 
328 /*
329  * Initialise the coherent pool for atomic allocations.
330  */
331 static int __init atomic_pool_init(void)
332 {
333 	struct dma_pool *pool = &atomic_pool;
334 	pgprot_t prot = pgprot_dmacoherent(pgprot_kernel);
335 	unsigned long nr_pages = pool->size >> PAGE_SHIFT;
336 	unsigned long *bitmap;
337 	struct page *page;
338 	struct page **pages;
339 	void *ptr;
340 	int bitmap_size = BITS_TO_LONGS(nr_pages) * sizeof(long);
341 
342 	bitmap = kzalloc(bitmap_size, GFP_KERNEL);
343 	if (!bitmap)
344 		goto no_bitmap;
345 
346 	pages = kzalloc(nr_pages * sizeof(struct page *), GFP_KERNEL);
347 	if (!pages)
348 		goto no_pages;
349 
350 	if (IS_ENABLED(CONFIG_CMA))
351 		ptr = __alloc_from_contiguous(NULL, pool->size, prot, &page);
352 	else
353 		ptr = __alloc_remap_buffer(NULL, pool->size, GFP_KERNEL, prot,
354 					   &page, NULL);
355 	if (ptr) {
356 		int i;
357 
358 		for (i = 0; i < nr_pages; i++)
359 			pages[i] = page + i;
360 
361 		spin_lock_init(&pool->lock);
362 		pool->vaddr = ptr;
363 		pool->pages = pages;
364 		pool->bitmap = bitmap;
365 		pool->nr_pages = nr_pages;
366 		pr_info("DMA: preallocated %u KiB pool for atomic coherent allocations\n",
367 		       (unsigned)pool->size / 1024);
368 		return 0;
369 	}
370 
371 	kfree(pages);
372 no_pages:
373 	kfree(bitmap);
374 no_bitmap:
375 	pr_err("DMA: failed to allocate %u KiB pool for atomic coherent allocation\n",
376 	       (unsigned)pool->size / 1024);
377 	return -ENOMEM;
378 }
379 /*
380  * CMA is activated by core_initcall, so we must be called after it.
381  */
382 postcore_initcall(atomic_pool_init);
383 
384 struct dma_contig_early_reserve {
385 	phys_addr_t base;
386 	unsigned long size;
387 };
388 
389 static struct dma_contig_early_reserve dma_mmu_remap[MAX_CMA_AREAS] __initdata;
390 
391 static int dma_mmu_remap_num __initdata;
392 
393 void __init dma_contiguous_early_fixup(phys_addr_t base, unsigned long size)
394 {
395 	dma_mmu_remap[dma_mmu_remap_num].base = base;
396 	dma_mmu_remap[dma_mmu_remap_num].size = size;
397 	dma_mmu_remap_num++;
398 }
399 
400 void __init dma_contiguous_remap(void)
401 {
402 	int i;
403 	for (i = 0; i < dma_mmu_remap_num; i++) {
404 		phys_addr_t start = dma_mmu_remap[i].base;
405 		phys_addr_t end = start + dma_mmu_remap[i].size;
406 		struct map_desc map;
407 		unsigned long addr;
408 
409 		if (end > arm_lowmem_limit)
410 			end = arm_lowmem_limit;
411 		if (start >= end)
412 			continue;
413 
414 		map.pfn = __phys_to_pfn(start);
415 		map.virtual = __phys_to_virt(start);
416 		map.length = end - start;
417 		map.type = MT_MEMORY_DMA_READY;
418 
419 		/*
420 		 * Clear previous low-memory mapping
421 		 */
422 		for (addr = __phys_to_virt(start); addr < __phys_to_virt(end);
423 		     addr += PMD_SIZE)
424 			pmd_clear(pmd_off_k(addr));
425 
426 		iotable_init(&map, 1);
427 	}
428 }
429 
430 static int __dma_update_pte(pte_t *pte, pgtable_t token, unsigned long addr,
431 			    void *data)
432 {
433 	struct page *page = virt_to_page(addr);
434 	pgprot_t prot = *(pgprot_t *)data;
435 
436 	set_pte_ext(pte, mk_pte(page, prot), 0);
437 	return 0;
438 }
439 
440 static void __dma_remap(struct page *page, size_t size, pgprot_t prot)
441 {
442 	unsigned long start = (unsigned long) page_address(page);
443 	unsigned end = start + size;
444 
445 	apply_to_page_range(&init_mm, start, size, __dma_update_pte, &prot);
446 	dsb();
447 	flush_tlb_kernel_range(start, end);
448 }
449 
450 static void *__alloc_remap_buffer(struct device *dev, size_t size, gfp_t gfp,
451 				 pgprot_t prot, struct page **ret_page,
452 				 const void *caller)
453 {
454 	struct page *page;
455 	void *ptr;
456 	page = __dma_alloc_buffer(dev, size, gfp);
457 	if (!page)
458 		return NULL;
459 
460 	ptr = __dma_alloc_remap(page, size, gfp, prot, caller);
461 	if (!ptr) {
462 		__dma_free_buffer(page, size);
463 		return NULL;
464 	}
465 
466 	*ret_page = page;
467 	return ptr;
468 }
469 
470 static void *__alloc_from_pool(size_t size, struct page **ret_page)
471 {
472 	struct dma_pool *pool = &atomic_pool;
473 	unsigned int count = PAGE_ALIGN(size) >> PAGE_SHIFT;
474 	unsigned int pageno;
475 	unsigned long flags;
476 	void *ptr = NULL;
477 	unsigned long align_mask;
478 
479 	if (!pool->vaddr) {
480 		WARN(1, "coherent pool not initialised!\n");
481 		return NULL;
482 	}
483 
484 	/*
485 	 * Align the region allocation - allocations from pool are rather
486 	 * small, so align them to their order in pages, minimum is a page
487 	 * size. This helps reduce fragmentation of the DMA space.
488 	 */
489 	align_mask = (1 << get_order(size)) - 1;
490 
491 	spin_lock_irqsave(&pool->lock, flags);
492 	pageno = bitmap_find_next_zero_area(pool->bitmap, pool->nr_pages,
493 					    0, count, align_mask);
494 	if (pageno < pool->nr_pages) {
495 		bitmap_set(pool->bitmap, pageno, count);
496 		ptr = pool->vaddr + PAGE_SIZE * pageno;
497 		*ret_page = pool->pages[pageno];
498 	} else {
499 		pr_err_once("ERROR: %u KiB atomic DMA coherent pool is too small!\n"
500 			    "Please increase it with coherent_pool= kernel parameter!\n",
501 			    (unsigned)pool->size / 1024);
502 	}
503 	spin_unlock_irqrestore(&pool->lock, flags);
504 
505 	return ptr;
506 }
507 
508 static bool __in_atomic_pool(void *start, size_t size)
509 {
510 	struct dma_pool *pool = &atomic_pool;
511 	void *end = start + size;
512 	void *pool_start = pool->vaddr;
513 	void *pool_end = pool->vaddr + pool->size;
514 
515 	if (start < pool_start || start >= pool_end)
516 		return false;
517 
518 	if (end <= pool_end)
519 		return true;
520 
521 	WARN(1, "Wrong coherent size(%p-%p) from atomic pool(%p-%p)\n",
522 	     start, end - 1, pool_start, pool_end - 1);
523 
524 	return false;
525 }
526 
527 static int __free_from_pool(void *start, size_t size)
528 {
529 	struct dma_pool *pool = &atomic_pool;
530 	unsigned long pageno, count;
531 	unsigned long flags;
532 
533 	if (!__in_atomic_pool(start, size))
534 		return 0;
535 
536 	pageno = (start - pool->vaddr) >> PAGE_SHIFT;
537 	count = size >> PAGE_SHIFT;
538 
539 	spin_lock_irqsave(&pool->lock, flags);
540 	bitmap_clear(pool->bitmap, pageno, count);
541 	spin_unlock_irqrestore(&pool->lock, flags);
542 
543 	return 1;
544 }
545 
546 static void *__alloc_from_contiguous(struct device *dev, size_t size,
547 				     pgprot_t prot, struct page **ret_page)
548 {
549 	unsigned long order = get_order(size);
550 	size_t count = size >> PAGE_SHIFT;
551 	struct page *page;
552 
553 	page = dma_alloc_from_contiguous(dev, count, order);
554 	if (!page)
555 		return NULL;
556 
557 	__dma_clear_buffer(page, size);
558 	__dma_remap(page, size, prot);
559 
560 	*ret_page = page;
561 	return page_address(page);
562 }
563 
564 static void __free_from_contiguous(struct device *dev, struct page *page,
565 				   size_t size)
566 {
567 	__dma_remap(page, size, pgprot_kernel);
568 	dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT);
569 }
570 
571 static inline pgprot_t __get_dma_pgprot(struct dma_attrs *attrs, pgprot_t prot)
572 {
573 	prot = dma_get_attr(DMA_ATTR_WRITE_COMBINE, attrs) ?
574 			    pgprot_writecombine(prot) :
575 			    pgprot_dmacoherent(prot);
576 	return prot;
577 }
578 
579 #define nommu() 0
580 
581 #else	/* !CONFIG_MMU */
582 
583 #define nommu() 1
584 
585 #define __get_dma_pgprot(attrs, prot)	__pgprot(0)
586 #define __alloc_remap_buffer(dev, size, gfp, prot, ret, c)	NULL
587 #define __alloc_from_pool(size, ret_page)			NULL
588 #define __alloc_from_contiguous(dev, size, prot, ret)		NULL
589 #define __free_from_pool(cpu_addr, size)			0
590 #define __free_from_contiguous(dev, page, size)			do { } while (0)
591 #define __dma_free_remap(cpu_addr, size)			do { } while (0)
592 
593 #endif	/* CONFIG_MMU */
594 
595 static void *__alloc_simple_buffer(struct device *dev, size_t size, gfp_t gfp,
596 				   struct page **ret_page)
597 {
598 	struct page *page;
599 	page = __dma_alloc_buffer(dev, size, gfp);
600 	if (!page)
601 		return NULL;
602 
603 	*ret_page = page;
604 	return page_address(page);
605 }
606 
607 
608 
609 static void *__dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
610 			 gfp_t gfp, pgprot_t prot, bool is_coherent, const void *caller)
611 {
612 	u64 mask = get_coherent_dma_mask(dev);
613 	struct page *page = NULL;
614 	void *addr;
615 
616 #ifdef CONFIG_DMA_API_DEBUG
617 	u64 limit = (mask + 1) & ~mask;
618 	if (limit && size >= limit) {
619 		dev_warn(dev, "coherent allocation too big (requested %#x mask %#llx)\n",
620 			size, mask);
621 		return NULL;
622 	}
623 #endif
624 
625 	if (!mask)
626 		return NULL;
627 
628 	if (mask < 0xffffffffULL)
629 		gfp |= GFP_DMA;
630 
631 	/*
632 	 * Following is a work-around (a.k.a. hack) to prevent pages
633 	 * with __GFP_COMP being passed to split_page() which cannot
634 	 * handle them.  The real problem is that this flag probably
635 	 * should be 0 on ARM as it is not supported on this
636 	 * platform; see CONFIG_HUGETLBFS.
637 	 */
638 	gfp &= ~(__GFP_COMP);
639 
640 	*handle = DMA_ERROR_CODE;
641 	size = PAGE_ALIGN(size);
642 
643 	if (is_coherent || nommu())
644 		addr = __alloc_simple_buffer(dev, size, gfp, &page);
645 	else if (gfp & GFP_ATOMIC)
646 		addr = __alloc_from_pool(size, &page);
647 	else if (!IS_ENABLED(CONFIG_CMA))
648 		addr = __alloc_remap_buffer(dev, size, gfp, prot, &page, caller);
649 	else
650 		addr = __alloc_from_contiguous(dev, size, prot, &page);
651 
652 	if (addr)
653 		*handle = pfn_to_dma(dev, page_to_pfn(page));
654 
655 	return addr;
656 }
657 
658 /*
659  * Allocate DMA-coherent memory space and return both the kernel remapped
660  * virtual and bus address for that space.
661  */
662 void *arm_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
663 		    gfp_t gfp, struct dma_attrs *attrs)
664 {
665 	pgprot_t prot = __get_dma_pgprot(attrs, pgprot_kernel);
666 	void *memory;
667 
668 	if (dma_alloc_from_coherent(dev, size, handle, &memory))
669 		return memory;
670 
671 	return __dma_alloc(dev, size, handle, gfp, prot, false,
672 			   __builtin_return_address(0));
673 }
674 
675 static void *arm_coherent_dma_alloc(struct device *dev, size_t size,
676 	dma_addr_t *handle, gfp_t gfp, struct dma_attrs *attrs)
677 {
678 	pgprot_t prot = __get_dma_pgprot(attrs, pgprot_kernel);
679 	void *memory;
680 
681 	if (dma_alloc_from_coherent(dev, size, handle, &memory))
682 		return memory;
683 
684 	return __dma_alloc(dev, size, handle, gfp, prot, true,
685 			   __builtin_return_address(0));
686 }
687 
688 /*
689  * Create userspace mapping for the DMA-coherent memory.
690  */
691 int arm_dma_mmap(struct device *dev, struct vm_area_struct *vma,
692 		 void *cpu_addr, dma_addr_t dma_addr, size_t size,
693 		 struct dma_attrs *attrs)
694 {
695 	int ret = -ENXIO;
696 #ifdef CONFIG_MMU
697 	unsigned long nr_vma_pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
698 	unsigned long nr_pages = PAGE_ALIGN(size) >> PAGE_SHIFT;
699 	unsigned long pfn = dma_to_pfn(dev, dma_addr);
700 	unsigned long off = vma->vm_pgoff;
701 
702 	vma->vm_page_prot = __get_dma_pgprot(attrs, vma->vm_page_prot);
703 
704 	if (dma_mmap_from_coherent(dev, vma, cpu_addr, size, &ret))
705 		return ret;
706 
707 	if (off < nr_pages && nr_vma_pages <= (nr_pages - off)) {
708 		ret = remap_pfn_range(vma, vma->vm_start,
709 				      pfn + off,
710 				      vma->vm_end - vma->vm_start,
711 				      vma->vm_page_prot);
712 	}
713 #endif	/* CONFIG_MMU */
714 
715 	return ret;
716 }
717 
718 /*
719  * Free a buffer as defined by the above mapping.
720  */
721 static void __arm_dma_free(struct device *dev, size_t size, void *cpu_addr,
722 			   dma_addr_t handle, struct dma_attrs *attrs,
723 			   bool is_coherent)
724 {
725 	struct page *page = pfn_to_page(dma_to_pfn(dev, handle));
726 
727 	if (dma_release_from_coherent(dev, get_order(size), cpu_addr))
728 		return;
729 
730 	size = PAGE_ALIGN(size);
731 
732 	if (is_coherent || nommu()) {
733 		__dma_free_buffer(page, size);
734 	} else if (__free_from_pool(cpu_addr, size)) {
735 		return;
736 	} else if (!IS_ENABLED(CONFIG_CMA)) {
737 		__dma_free_remap(cpu_addr, size);
738 		__dma_free_buffer(page, size);
739 	} else {
740 		/*
741 		 * Non-atomic allocations cannot be freed with IRQs disabled
742 		 */
743 		WARN_ON(irqs_disabled());
744 		__free_from_contiguous(dev, page, size);
745 	}
746 }
747 
748 void arm_dma_free(struct device *dev, size_t size, void *cpu_addr,
749 		  dma_addr_t handle, struct dma_attrs *attrs)
750 {
751 	__arm_dma_free(dev, size, cpu_addr, handle, attrs, false);
752 }
753 
754 static void arm_coherent_dma_free(struct device *dev, size_t size, void *cpu_addr,
755 				  dma_addr_t handle, struct dma_attrs *attrs)
756 {
757 	__arm_dma_free(dev, size, cpu_addr, handle, attrs, true);
758 }
759 
760 int arm_dma_get_sgtable(struct device *dev, struct sg_table *sgt,
761 		 void *cpu_addr, dma_addr_t handle, size_t size,
762 		 struct dma_attrs *attrs)
763 {
764 	struct page *page = pfn_to_page(dma_to_pfn(dev, handle));
765 	int ret;
766 
767 	ret = sg_alloc_table(sgt, 1, GFP_KERNEL);
768 	if (unlikely(ret))
769 		return ret;
770 
771 	sg_set_page(sgt->sgl, page, PAGE_ALIGN(size), 0);
772 	return 0;
773 }
774 
775 static void dma_cache_maint_page(struct page *page, unsigned long offset,
776 	size_t size, enum dma_data_direction dir,
777 	void (*op)(const void *, size_t, int))
778 {
779 	/*
780 	 * A single sg entry may refer to multiple physically contiguous
781 	 * pages.  But we still need to process highmem pages individually.
782 	 * If highmem is not configured then the bulk of this loop gets
783 	 * optimized out.
784 	 */
785 	size_t left = size;
786 	do {
787 		size_t len = left;
788 		void *vaddr;
789 
790 		if (PageHighMem(page)) {
791 			if (len + offset > PAGE_SIZE) {
792 				if (offset >= PAGE_SIZE) {
793 					page += offset / PAGE_SIZE;
794 					offset %= PAGE_SIZE;
795 				}
796 				len = PAGE_SIZE - offset;
797 			}
798 			vaddr = kmap_high_get(page);
799 			if (vaddr) {
800 				vaddr += offset;
801 				op(vaddr, len, dir);
802 				kunmap_high(page);
803 			} else if (cache_is_vipt()) {
804 				/* unmapped pages might still be cached */
805 				vaddr = kmap_atomic(page);
806 				op(vaddr + offset, len, dir);
807 				kunmap_atomic(vaddr);
808 			}
809 		} else {
810 			vaddr = page_address(page) + offset;
811 			op(vaddr, len, dir);
812 		}
813 		offset = 0;
814 		page++;
815 		left -= len;
816 	} while (left);
817 }
818 
819 /*
820  * Make an area consistent for devices.
821  * Note: Drivers should NOT use this function directly, as it will break
822  * platforms with CONFIG_DMABOUNCE.
823  * Use the driver DMA support - see dma-mapping.h (dma_sync_*)
824  */
825 static void __dma_page_cpu_to_dev(struct page *page, unsigned long off,
826 	size_t size, enum dma_data_direction dir)
827 {
828 	unsigned long paddr;
829 
830 	dma_cache_maint_page(page, off, size, dir, dmac_map_area);
831 
832 	paddr = page_to_phys(page) + off;
833 	if (dir == DMA_FROM_DEVICE) {
834 		outer_inv_range(paddr, paddr + size);
835 	} else {
836 		outer_clean_range(paddr, paddr + size);
837 	}
838 	/* FIXME: non-speculating: flush on bidirectional mappings? */
839 }
840 
841 static void __dma_page_dev_to_cpu(struct page *page, unsigned long off,
842 	size_t size, enum dma_data_direction dir)
843 {
844 	unsigned long paddr = page_to_phys(page) + off;
845 
846 	/* FIXME: non-speculating: not required */
847 	/* don't bother invalidating if DMA to device */
848 	if (dir != DMA_TO_DEVICE)
849 		outer_inv_range(paddr, paddr + size);
850 
851 	dma_cache_maint_page(page, off, size, dir, dmac_unmap_area);
852 
853 	/*
854 	 * Mark the D-cache clean for this page to avoid extra flushing.
855 	 */
856 	if (dir != DMA_TO_DEVICE && off == 0 && size >= PAGE_SIZE)
857 		set_bit(PG_dcache_clean, &page->flags);
858 }
859 
860 /**
861  * arm_dma_map_sg - map a set of SG buffers for streaming mode DMA
862  * @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
863  * @sg: list of buffers
864  * @nents: number of buffers to map
865  * @dir: DMA transfer direction
866  *
867  * Map a set of buffers described by scatterlist in streaming mode for DMA.
868  * This is the scatter-gather version of the dma_map_single interface.
869  * Here the scatter gather list elements are each tagged with the
870  * appropriate dma address and length.  They are obtained via
871  * sg_dma_{address,length}.
872  *
873  * Device ownership issues as mentioned for dma_map_single are the same
874  * here.
875  */
876 int arm_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
877 		enum dma_data_direction dir, struct dma_attrs *attrs)
878 {
879 	struct dma_map_ops *ops = get_dma_ops(dev);
880 	struct scatterlist *s;
881 	int i, j;
882 
883 	for_each_sg(sg, s, nents, i) {
884 #ifdef CONFIG_NEED_SG_DMA_LENGTH
885 		s->dma_length = s->length;
886 #endif
887 		s->dma_address = ops->map_page(dev, sg_page(s), s->offset,
888 						s->length, dir, attrs);
889 		if (dma_mapping_error(dev, s->dma_address))
890 			goto bad_mapping;
891 	}
892 	return nents;
893 
894  bad_mapping:
895 	for_each_sg(sg, s, i, j)
896 		ops->unmap_page(dev, sg_dma_address(s), sg_dma_len(s), dir, attrs);
897 	return 0;
898 }
899 
900 /**
901  * arm_dma_unmap_sg - unmap a set of SG buffers mapped by dma_map_sg
902  * @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
903  * @sg: list of buffers
904  * @nents: number of buffers to unmap (same as was passed to dma_map_sg)
905  * @dir: DMA transfer direction (same as was passed to dma_map_sg)
906  *
907  * Unmap a set of streaming mode DMA translations.  Again, CPU access
908  * rules concerning calls here are the same as for dma_unmap_single().
909  */
910 void arm_dma_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
911 		enum dma_data_direction dir, struct dma_attrs *attrs)
912 {
913 	struct dma_map_ops *ops = get_dma_ops(dev);
914 	struct scatterlist *s;
915 
916 	int i;
917 
918 	for_each_sg(sg, s, nents, i)
919 		ops->unmap_page(dev, sg_dma_address(s), sg_dma_len(s), dir, attrs);
920 }
921 
922 /**
923  * arm_dma_sync_sg_for_cpu
924  * @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
925  * @sg: list of buffers
926  * @nents: number of buffers to map (returned from dma_map_sg)
927  * @dir: DMA transfer direction (same as was passed to dma_map_sg)
928  */
929 void arm_dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
930 			int nents, enum dma_data_direction dir)
931 {
932 	struct dma_map_ops *ops = get_dma_ops(dev);
933 	struct scatterlist *s;
934 	int i;
935 
936 	for_each_sg(sg, s, nents, i)
937 		ops->sync_single_for_cpu(dev, sg_dma_address(s), s->length,
938 					 dir);
939 }
940 
941 /**
942  * arm_dma_sync_sg_for_device
943  * @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
944  * @sg: list of buffers
945  * @nents: number of buffers to map (returned from dma_map_sg)
946  * @dir: DMA transfer direction (same as was passed to dma_map_sg)
947  */
948 void arm_dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
949 			int nents, enum dma_data_direction dir)
950 {
951 	struct dma_map_ops *ops = get_dma_ops(dev);
952 	struct scatterlist *s;
953 	int i;
954 
955 	for_each_sg(sg, s, nents, i)
956 		ops->sync_single_for_device(dev, sg_dma_address(s), s->length,
957 					    dir);
958 }
959 
960 /*
961  * Return whether the given device DMA address mask can be supported
962  * properly.  For example, if your device can only drive the low 24-bits
963  * during bus mastering, then you would pass 0x00ffffff as the mask
964  * to this function.
965  */
966 int dma_supported(struct device *dev, u64 mask)
967 {
968 	if (mask < (u64)arm_dma_limit)
969 		return 0;
970 	return 1;
971 }
972 EXPORT_SYMBOL(dma_supported);
973 
974 static int arm_dma_set_mask(struct device *dev, u64 dma_mask)
975 {
976 	if (!dev->dma_mask || !dma_supported(dev, dma_mask))
977 		return -EIO;
978 
979 	*dev->dma_mask = dma_mask;
980 
981 	return 0;
982 }
983 
984 #define PREALLOC_DMA_DEBUG_ENTRIES	4096
985 
986 static int __init dma_debug_do_init(void)
987 {
988 	dma_debug_init(PREALLOC_DMA_DEBUG_ENTRIES);
989 	return 0;
990 }
991 fs_initcall(dma_debug_do_init);
992 
993 #ifdef CONFIG_ARM_DMA_USE_IOMMU
994 
995 /* IOMMU */
996 
997 static inline dma_addr_t __alloc_iova(struct dma_iommu_mapping *mapping,
998 				      size_t size)
999 {
1000 	unsigned int order = get_order(size);
1001 	unsigned int align = 0;
1002 	unsigned int count, start;
1003 	unsigned long flags;
1004 
1005 	count = ((PAGE_ALIGN(size) >> PAGE_SHIFT) +
1006 		 (1 << mapping->order) - 1) >> mapping->order;
1007 
1008 	if (order > mapping->order)
1009 		align = (1 << (order - mapping->order)) - 1;
1010 
1011 	spin_lock_irqsave(&mapping->lock, flags);
1012 	start = bitmap_find_next_zero_area(mapping->bitmap, mapping->bits, 0,
1013 					   count, align);
1014 	if (start > mapping->bits) {
1015 		spin_unlock_irqrestore(&mapping->lock, flags);
1016 		return DMA_ERROR_CODE;
1017 	}
1018 
1019 	bitmap_set(mapping->bitmap, start, count);
1020 	spin_unlock_irqrestore(&mapping->lock, flags);
1021 
1022 	return mapping->base + (start << (mapping->order + PAGE_SHIFT));
1023 }
1024 
1025 static inline void __free_iova(struct dma_iommu_mapping *mapping,
1026 			       dma_addr_t addr, size_t size)
1027 {
1028 	unsigned int start = (addr - mapping->base) >>
1029 			     (mapping->order + PAGE_SHIFT);
1030 	unsigned int count = ((size >> PAGE_SHIFT) +
1031 			      (1 << mapping->order) - 1) >> mapping->order;
1032 	unsigned long flags;
1033 
1034 	spin_lock_irqsave(&mapping->lock, flags);
1035 	bitmap_clear(mapping->bitmap, start, count);
1036 	spin_unlock_irqrestore(&mapping->lock, flags);
1037 }
1038 
1039 static struct page **__iommu_alloc_buffer(struct device *dev, size_t size, gfp_t gfp)
1040 {
1041 	struct page **pages;
1042 	int count = size >> PAGE_SHIFT;
1043 	int array_size = count * sizeof(struct page *);
1044 	int i = 0;
1045 
1046 	if (array_size <= PAGE_SIZE)
1047 		pages = kzalloc(array_size, gfp);
1048 	else
1049 		pages = vzalloc(array_size);
1050 	if (!pages)
1051 		return NULL;
1052 
1053 	while (count) {
1054 		int j, order = __fls(count);
1055 
1056 		pages[i] = alloc_pages(gfp | __GFP_NOWARN, order);
1057 		while (!pages[i] && order)
1058 			pages[i] = alloc_pages(gfp | __GFP_NOWARN, --order);
1059 		if (!pages[i])
1060 			goto error;
1061 
1062 		if (order) {
1063 			split_page(pages[i], order);
1064 			j = 1 << order;
1065 			while (--j)
1066 				pages[i + j] = pages[i] + j;
1067 		}
1068 
1069 		__dma_clear_buffer(pages[i], PAGE_SIZE << order);
1070 		i += 1 << order;
1071 		count -= 1 << order;
1072 	}
1073 
1074 	return pages;
1075 error:
1076 	while (i--)
1077 		if (pages[i])
1078 			__free_pages(pages[i], 0);
1079 	if (array_size <= PAGE_SIZE)
1080 		kfree(pages);
1081 	else
1082 		vfree(pages);
1083 	return NULL;
1084 }
1085 
1086 static int __iommu_free_buffer(struct device *dev, struct page **pages, size_t size)
1087 {
1088 	int count = size >> PAGE_SHIFT;
1089 	int array_size = count * sizeof(struct page *);
1090 	int i;
1091 	for (i = 0; i < count; i++)
1092 		if (pages[i])
1093 			__free_pages(pages[i], 0);
1094 	if (array_size <= PAGE_SIZE)
1095 		kfree(pages);
1096 	else
1097 		vfree(pages);
1098 	return 0;
1099 }
1100 
1101 /*
1102  * Create a CPU mapping for a specified pages
1103  */
1104 static void *
1105 __iommu_alloc_remap(struct page **pages, size_t size, gfp_t gfp, pgprot_t prot,
1106 		    const void *caller)
1107 {
1108 	unsigned int i, nr_pages = PAGE_ALIGN(size) >> PAGE_SHIFT;
1109 	struct vm_struct *area;
1110 	unsigned long p;
1111 
1112 	area = get_vm_area_caller(size, VM_ARM_DMA_CONSISTENT | VM_USERMAP,
1113 				  caller);
1114 	if (!area)
1115 		return NULL;
1116 
1117 	area->pages = pages;
1118 	area->nr_pages = nr_pages;
1119 	p = (unsigned long)area->addr;
1120 
1121 	for (i = 0; i < nr_pages; i++) {
1122 		phys_addr_t phys = __pfn_to_phys(page_to_pfn(pages[i]));
1123 		if (ioremap_page_range(p, p + PAGE_SIZE, phys, prot))
1124 			goto err;
1125 		p += PAGE_SIZE;
1126 	}
1127 	return area->addr;
1128 err:
1129 	unmap_kernel_range((unsigned long)area->addr, size);
1130 	vunmap(area->addr);
1131 	return NULL;
1132 }
1133 
1134 /*
1135  * Create a mapping in device IO address space for specified pages
1136  */
1137 static dma_addr_t
1138 __iommu_create_mapping(struct device *dev, struct page **pages, size_t size)
1139 {
1140 	struct dma_iommu_mapping *mapping = dev->archdata.mapping;
1141 	unsigned int count = PAGE_ALIGN(size) >> PAGE_SHIFT;
1142 	dma_addr_t dma_addr, iova;
1143 	int i, ret = DMA_ERROR_CODE;
1144 
1145 	dma_addr = __alloc_iova(mapping, size);
1146 	if (dma_addr == DMA_ERROR_CODE)
1147 		return dma_addr;
1148 
1149 	iova = dma_addr;
1150 	for (i = 0; i < count; ) {
1151 		unsigned int next_pfn = page_to_pfn(pages[i]) + 1;
1152 		phys_addr_t phys = page_to_phys(pages[i]);
1153 		unsigned int len, j;
1154 
1155 		for (j = i + 1; j < count; j++, next_pfn++)
1156 			if (page_to_pfn(pages[j]) != next_pfn)
1157 				break;
1158 
1159 		len = (j - i) << PAGE_SHIFT;
1160 		ret = iommu_map(mapping->domain, iova, phys, len, 0);
1161 		if (ret < 0)
1162 			goto fail;
1163 		iova += len;
1164 		i = j;
1165 	}
1166 	return dma_addr;
1167 fail:
1168 	iommu_unmap(mapping->domain, dma_addr, iova-dma_addr);
1169 	__free_iova(mapping, dma_addr, size);
1170 	return DMA_ERROR_CODE;
1171 }
1172 
1173 static int __iommu_remove_mapping(struct device *dev, dma_addr_t iova, size_t size)
1174 {
1175 	struct dma_iommu_mapping *mapping = dev->archdata.mapping;
1176 
1177 	/*
1178 	 * add optional in-page offset from iova to size and align
1179 	 * result to page size
1180 	 */
1181 	size = PAGE_ALIGN((iova & ~PAGE_MASK) + size);
1182 	iova &= PAGE_MASK;
1183 
1184 	iommu_unmap(mapping->domain, iova, size);
1185 	__free_iova(mapping, iova, size);
1186 	return 0;
1187 }
1188 
1189 static struct page **__atomic_get_pages(void *addr)
1190 {
1191 	struct dma_pool *pool = &atomic_pool;
1192 	struct page **pages = pool->pages;
1193 	int offs = (addr - pool->vaddr) >> PAGE_SHIFT;
1194 
1195 	return pages + offs;
1196 }
1197 
1198 static struct page **__iommu_get_pages(void *cpu_addr, struct dma_attrs *attrs)
1199 {
1200 	struct vm_struct *area;
1201 
1202 	if (__in_atomic_pool(cpu_addr, PAGE_SIZE))
1203 		return __atomic_get_pages(cpu_addr);
1204 
1205 	if (dma_get_attr(DMA_ATTR_NO_KERNEL_MAPPING, attrs))
1206 		return cpu_addr;
1207 
1208 	area = find_vm_area(cpu_addr);
1209 	if (area && (area->flags & VM_ARM_DMA_CONSISTENT))
1210 		return area->pages;
1211 	return NULL;
1212 }
1213 
1214 static void *__iommu_alloc_atomic(struct device *dev, size_t size,
1215 				  dma_addr_t *handle)
1216 {
1217 	struct page *page;
1218 	void *addr;
1219 
1220 	addr = __alloc_from_pool(size, &page);
1221 	if (!addr)
1222 		return NULL;
1223 
1224 	*handle = __iommu_create_mapping(dev, &page, size);
1225 	if (*handle == DMA_ERROR_CODE)
1226 		goto err_mapping;
1227 
1228 	return addr;
1229 
1230 err_mapping:
1231 	__free_from_pool(addr, size);
1232 	return NULL;
1233 }
1234 
1235 static void __iommu_free_atomic(struct device *dev, struct page **pages,
1236 				dma_addr_t handle, size_t size)
1237 {
1238 	__iommu_remove_mapping(dev, handle, size);
1239 	__free_from_pool(page_address(pages[0]), size);
1240 }
1241 
1242 static void *arm_iommu_alloc_attrs(struct device *dev, size_t size,
1243 	    dma_addr_t *handle, gfp_t gfp, struct dma_attrs *attrs)
1244 {
1245 	pgprot_t prot = __get_dma_pgprot(attrs, pgprot_kernel);
1246 	struct page **pages;
1247 	void *addr = NULL;
1248 
1249 	*handle = DMA_ERROR_CODE;
1250 	size = PAGE_ALIGN(size);
1251 
1252 	if (gfp & GFP_ATOMIC)
1253 		return __iommu_alloc_atomic(dev, size, handle);
1254 
1255 	pages = __iommu_alloc_buffer(dev, size, gfp);
1256 	if (!pages)
1257 		return NULL;
1258 
1259 	*handle = __iommu_create_mapping(dev, pages, size);
1260 	if (*handle == DMA_ERROR_CODE)
1261 		goto err_buffer;
1262 
1263 	if (dma_get_attr(DMA_ATTR_NO_KERNEL_MAPPING, attrs))
1264 		return pages;
1265 
1266 	addr = __iommu_alloc_remap(pages, size, gfp, prot,
1267 				   __builtin_return_address(0));
1268 	if (!addr)
1269 		goto err_mapping;
1270 
1271 	return addr;
1272 
1273 err_mapping:
1274 	__iommu_remove_mapping(dev, *handle, size);
1275 err_buffer:
1276 	__iommu_free_buffer(dev, pages, size);
1277 	return NULL;
1278 }
1279 
1280 static int arm_iommu_mmap_attrs(struct device *dev, struct vm_area_struct *vma,
1281 		    void *cpu_addr, dma_addr_t dma_addr, size_t size,
1282 		    struct dma_attrs *attrs)
1283 {
1284 	unsigned long uaddr = vma->vm_start;
1285 	unsigned long usize = vma->vm_end - vma->vm_start;
1286 	struct page **pages = __iommu_get_pages(cpu_addr, attrs);
1287 
1288 	vma->vm_page_prot = __get_dma_pgprot(attrs, vma->vm_page_prot);
1289 
1290 	if (!pages)
1291 		return -ENXIO;
1292 
1293 	do {
1294 		int ret = vm_insert_page(vma, uaddr, *pages++);
1295 		if (ret) {
1296 			pr_err("Remapping memory failed: %d\n", ret);
1297 			return ret;
1298 		}
1299 		uaddr += PAGE_SIZE;
1300 		usize -= PAGE_SIZE;
1301 	} while (usize > 0);
1302 
1303 	return 0;
1304 }
1305 
1306 /*
1307  * free a page as defined by the above mapping.
1308  * Must not be called with IRQs disabled.
1309  */
1310 void arm_iommu_free_attrs(struct device *dev, size_t size, void *cpu_addr,
1311 			  dma_addr_t handle, struct dma_attrs *attrs)
1312 {
1313 	struct page **pages = __iommu_get_pages(cpu_addr, attrs);
1314 	size = PAGE_ALIGN(size);
1315 
1316 	if (!pages) {
1317 		WARN(1, "trying to free invalid coherent area: %p\n", cpu_addr);
1318 		return;
1319 	}
1320 
1321 	if (__in_atomic_pool(cpu_addr, size)) {
1322 		__iommu_free_atomic(dev, pages, handle, size);
1323 		return;
1324 	}
1325 
1326 	if (!dma_get_attr(DMA_ATTR_NO_KERNEL_MAPPING, attrs)) {
1327 		unmap_kernel_range((unsigned long)cpu_addr, size);
1328 		vunmap(cpu_addr);
1329 	}
1330 
1331 	__iommu_remove_mapping(dev, handle, size);
1332 	__iommu_free_buffer(dev, pages, size);
1333 }
1334 
1335 static int arm_iommu_get_sgtable(struct device *dev, struct sg_table *sgt,
1336 				 void *cpu_addr, dma_addr_t dma_addr,
1337 				 size_t size, struct dma_attrs *attrs)
1338 {
1339 	unsigned int count = PAGE_ALIGN(size) >> PAGE_SHIFT;
1340 	struct page **pages = __iommu_get_pages(cpu_addr, attrs);
1341 
1342 	if (!pages)
1343 		return -ENXIO;
1344 
1345 	return sg_alloc_table_from_pages(sgt, pages, count, 0, size,
1346 					 GFP_KERNEL);
1347 }
1348 
1349 /*
1350  * Map a part of the scatter-gather list into contiguous io address space
1351  */
1352 static int __map_sg_chunk(struct device *dev, struct scatterlist *sg,
1353 			  size_t size, dma_addr_t *handle,
1354 			  enum dma_data_direction dir, struct dma_attrs *attrs,
1355 			  bool is_coherent)
1356 {
1357 	struct dma_iommu_mapping *mapping = dev->archdata.mapping;
1358 	dma_addr_t iova, iova_base;
1359 	int ret = 0;
1360 	unsigned int count;
1361 	struct scatterlist *s;
1362 
1363 	size = PAGE_ALIGN(size);
1364 	*handle = DMA_ERROR_CODE;
1365 
1366 	iova_base = iova = __alloc_iova(mapping, size);
1367 	if (iova == DMA_ERROR_CODE)
1368 		return -ENOMEM;
1369 
1370 	for (count = 0, s = sg; count < (size >> PAGE_SHIFT); s = sg_next(s)) {
1371 		phys_addr_t phys = page_to_phys(sg_page(s));
1372 		unsigned int len = PAGE_ALIGN(s->offset + s->length);
1373 
1374 		if (!is_coherent &&
1375 			!dma_get_attr(DMA_ATTR_SKIP_CPU_SYNC, attrs))
1376 			__dma_page_cpu_to_dev(sg_page(s), s->offset, s->length, dir);
1377 
1378 		ret = iommu_map(mapping->domain, iova, phys, len, 0);
1379 		if (ret < 0)
1380 			goto fail;
1381 		count += len >> PAGE_SHIFT;
1382 		iova += len;
1383 	}
1384 	*handle = iova_base;
1385 
1386 	return 0;
1387 fail:
1388 	iommu_unmap(mapping->domain, iova_base, count * PAGE_SIZE);
1389 	__free_iova(mapping, iova_base, size);
1390 	return ret;
1391 }
1392 
1393 static int __iommu_map_sg(struct device *dev, struct scatterlist *sg, int nents,
1394 		     enum dma_data_direction dir, struct dma_attrs *attrs,
1395 		     bool is_coherent)
1396 {
1397 	struct scatterlist *s = sg, *dma = sg, *start = sg;
1398 	int i, count = 0;
1399 	unsigned int offset = s->offset;
1400 	unsigned int size = s->offset + s->length;
1401 	unsigned int max = dma_get_max_seg_size(dev);
1402 
1403 	for (i = 1; i < nents; i++) {
1404 		s = sg_next(s);
1405 
1406 		s->dma_address = DMA_ERROR_CODE;
1407 		s->dma_length = 0;
1408 
1409 		if (s->offset || (size & ~PAGE_MASK) || size + s->length > max) {
1410 			if (__map_sg_chunk(dev, start, size, &dma->dma_address,
1411 			    dir, attrs, is_coherent) < 0)
1412 				goto bad_mapping;
1413 
1414 			dma->dma_address += offset;
1415 			dma->dma_length = size - offset;
1416 
1417 			size = offset = s->offset;
1418 			start = s;
1419 			dma = sg_next(dma);
1420 			count += 1;
1421 		}
1422 		size += s->length;
1423 	}
1424 	if (__map_sg_chunk(dev, start, size, &dma->dma_address, dir, attrs,
1425 		is_coherent) < 0)
1426 		goto bad_mapping;
1427 
1428 	dma->dma_address += offset;
1429 	dma->dma_length = size - offset;
1430 
1431 	return count+1;
1432 
1433 bad_mapping:
1434 	for_each_sg(sg, s, count, i)
1435 		__iommu_remove_mapping(dev, sg_dma_address(s), sg_dma_len(s));
1436 	return 0;
1437 }
1438 
1439 /**
1440  * arm_coherent_iommu_map_sg - map a set of SG buffers for streaming mode DMA
1441  * @dev: valid struct device pointer
1442  * @sg: list of buffers
1443  * @nents: number of buffers to map
1444  * @dir: DMA transfer direction
1445  *
1446  * Map a set of i/o coherent buffers described by scatterlist in streaming
1447  * mode for DMA. The scatter gather list elements are merged together (if
1448  * possible) and tagged with the appropriate dma address and length. They are
1449  * obtained via sg_dma_{address,length}.
1450  */
1451 int arm_coherent_iommu_map_sg(struct device *dev, struct scatterlist *sg,
1452 		int nents, enum dma_data_direction dir, struct dma_attrs *attrs)
1453 {
1454 	return __iommu_map_sg(dev, sg, nents, dir, attrs, true);
1455 }
1456 
1457 /**
1458  * arm_iommu_map_sg - map a set of SG buffers for streaming mode DMA
1459  * @dev: valid struct device pointer
1460  * @sg: list of buffers
1461  * @nents: number of buffers to map
1462  * @dir: DMA transfer direction
1463  *
1464  * Map a set of buffers described by scatterlist in streaming mode for DMA.
1465  * The scatter gather list elements are merged together (if possible) and
1466  * tagged with the appropriate dma address and length. They are obtained via
1467  * sg_dma_{address,length}.
1468  */
1469 int arm_iommu_map_sg(struct device *dev, struct scatterlist *sg,
1470 		int nents, enum dma_data_direction dir, struct dma_attrs *attrs)
1471 {
1472 	return __iommu_map_sg(dev, sg, nents, dir, attrs, false);
1473 }
1474 
1475 static void __iommu_unmap_sg(struct device *dev, struct scatterlist *sg,
1476 		int nents, enum dma_data_direction dir, struct dma_attrs *attrs,
1477 		bool is_coherent)
1478 {
1479 	struct scatterlist *s;
1480 	int i;
1481 
1482 	for_each_sg(sg, s, nents, i) {
1483 		if (sg_dma_len(s))
1484 			__iommu_remove_mapping(dev, sg_dma_address(s),
1485 					       sg_dma_len(s));
1486 		if (!is_coherent &&
1487 		    !dma_get_attr(DMA_ATTR_SKIP_CPU_SYNC, attrs))
1488 			__dma_page_dev_to_cpu(sg_page(s), s->offset,
1489 					      s->length, dir);
1490 	}
1491 }
1492 
1493 /**
1494  * arm_coherent_iommu_unmap_sg - unmap a set of SG buffers mapped by dma_map_sg
1495  * @dev: valid struct device pointer
1496  * @sg: list of buffers
1497  * @nents: number of buffers to unmap (same as was passed to dma_map_sg)
1498  * @dir: DMA transfer direction (same as was passed to dma_map_sg)
1499  *
1500  * Unmap a set of streaming mode DMA translations.  Again, CPU access
1501  * rules concerning calls here are the same as for dma_unmap_single().
1502  */
1503 void arm_coherent_iommu_unmap_sg(struct device *dev, struct scatterlist *sg,
1504 		int nents, enum dma_data_direction dir, struct dma_attrs *attrs)
1505 {
1506 	__iommu_unmap_sg(dev, sg, nents, dir, attrs, true);
1507 }
1508 
1509 /**
1510  * arm_iommu_unmap_sg - unmap a set of SG buffers mapped by dma_map_sg
1511  * @dev: valid struct device pointer
1512  * @sg: list of buffers
1513  * @nents: number of buffers to unmap (same as was passed to dma_map_sg)
1514  * @dir: DMA transfer direction (same as was passed to dma_map_sg)
1515  *
1516  * Unmap a set of streaming mode DMA translations.  Again, CPU access
1517  * rules concerning calls here are the same as for dma_unmap_single().
1518  */
1519 void arm_iommu_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
1520 			enum dma_data_direction dir, struct dma_attrs *attrs)
1521 {
1522 	__iommu_unmap_sg(dev, sg, nents, dir, attrs, false);
1523 }
1524 
1525 /**
1526  * arm_iommu_sync_sg_for_cpu
1527  * @dev: valid struct device pointer
1528  * @sg: list of buffers
1529  * @nents: number of buffers to map (returned from dma_map_sg)
1530  * @dir: DMA transfer direction (same as was passed to dma_map_sg)
1531  */
1532 void arm_iommu_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
1533 			int nents, enum dma_data_direction dir)
1534 {
1535 	struct scatterlist *s;
1536 	int i;
1537 
1538 	for_each_sg(sg, s, nents, i)
1539 		__dma_page_dev_to_cpu(sg_page(s), s->offset, s->length, dir);
1540 
1541 }
1542 
1543 /**
1544  * arm_iommu_sync_sg_for_device
1545  * @dev: valid struct device pointer
1546  * @sg: list of buffers
1547  * @nents: number of buffers to map (returned from dma_map_sg)
1548  * @dir: DMA transfer direction (same as was passed to dma_map_sg)
1549  */
1550 void arm_iommu_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
1551 			int nents, enum dma_data_direction dir)
1552 {
1553 	struct scatterlist *s;
1554 	int i;
1555 
1556 	for_each_sg(sg, s, nents, i)
1557 		__dma_page_cpu_to_dev(sg_page(s), s->offset, s->length, dir);
1558 }
1559 
1560 
1561 /**
1562  * arm_coherent_iommu_map_page
1563  * @dev: valid struct device pointer
1564  * @page: page that buffer resides in
1565  * @offset: offset into page for start of buffer
1566  * @size: size of buffer to map
1567  * @dir: DMA transfer direction
1568  *
1569  * Coherent IOMMU aware version of arm_dma_map_page()
1570  */
1571 static dma_addr_t arm_coherent_iommu_map_page(struct device *dev, struct page *page,
1572 	     unsigned long offset, size_t size, enum dma_data_direction dir,
1573 	     struct dma_attrs *attrs)
1574 {
1575 	struct dma_iommu_mapping *mapping = dev->archdata.mapping;
1576 	dma_addr_t dma_addr;
1577 	int ret, len = PAGE_ALIGN(size + offset);
1578 
1579 	dma_addr = __alloc_iova(mapping, len);
1580 	if (dma_addr == DMA_ERROR_CODE)
1581 		return dma_addr;
1582 
1583 	ret = iommu_map(mapping->domain, dma_addr, page_to_phys(page), len, 0);
1584 	if (ret < 0)
1585 		goto fail;
1586 
1587 	return dma_addr + offset;
1588 fail:
1589 	__free_iova(mapping, dma_addr, len);
1590 	return DMA_ERROR_CODE;
1591 }
1592 
1593 /**
1594  * arm_iommu_map_page
1595  * @dev: valid struct device pointer
1596  * @page: page that buffer resides in
1597  * @offset: offset into page for start of buffer
1598  * @size: size of buffer to map
1599  * @dir: DMA transfer direction
1600  *
1601  * IOMMU aware version of arm_dma_map_page()
1602  */
1603 static dma_addr_t arm_iommu_map_page(struct device *dev, struct page *page,
1604 	     unsigned long offset, size_t size, enum dma_data_direction dir,
1605 	     struct dma_attrs *attrs)
1606 {
1607 	if (!dma_get_attr(DMA_ATTR_SKIP_CPU_SYNC, attrs))
1608 		__dma_page_cpu_to_dev(page, offset, size, dir);
1609 
1610 	return arm_coherent_iommu_map_page(dev, page, offset, size, dir, attrs);
1611 }
1612 
1613 /**
1614  * arm_coherent_iommu_unmap_page
1615  * @dev: valid struct device pointer
1616  * @handle: DMA address of buffer
1617  * @size: size of buffer (same as passed to dma_map_page)
1618  * @dir: DMA transfer direction (same as passed to dma_map_page)
1619  *
1620  * Coherent IOMMU aware version of arm_dma_unmap_page()
1621  */
1622 static void arm_coherent_iommu_unmap_page(struct device *dev, dma_addr_t handle,
1623 		size_t size, enum dma_data_direction dir,
1624 		struct dma_attrs *attrs)
1625 {
1626 	struct dma_iommu_mapping *mapping = dev->archdata.mapping;
1627 	dma_addr_t iova = handle & PAGE_MASK;
1628 	int offset = handle & ~PAGE_MASK;
1629 	int len = PAGE_ALIGN(size + offset);
1630 
1631 	if (!iova)
1632 		return;
1633 
1634 	iommu_unmap(mapping->domain, iova, len);
1635 	__free_iova(mapping, iova, len);
1636 }
1637 
1638 /**
1639  * arm_iommu_unmap_page
1640  * @dev: valid struct device pointer
1641  * @handle: DMA address of buffer
1642  * @size: size of buffer (same as passed to dma_map_page)
1643  * @dir: DMA transfer direction (same as passed to dma_map_page)
1644  *
1645  * IOMMU aware version of arm_dma_unmap_page()
1646  */
1647 static void arm_iommu_unmap_page(struct device *dev, dma_addr_t handle,
1648 		size_t size, enum dma_data_direction dir,
1649 		struct dma_attrs *attrs)
1650 {
1651 	struct dma_iommu_mapping *mapping = dev->archdata.mapping;
1652 	dma_addr_t iova = handle & PAGE_MASK;
1653 	struct page *page = phys_to_page(iommu_iova_to_phys(mapping->domain, iova));
1654 	int offset = handle & ~PAGE_MASK;
1655 	int len = PAGE_ALIGN(size + offset);
1656 
1657 	if (!iova)
1658 		return;
1659 
1660 	if (!dma_get_attr(DMA_ATTR_SKIP_CPU_SYNC, attrs))
1661 		__dma_page_dev_to_cpu(page, offset, size, dir);
1662 
1663 	iommu_unmap(mapping->domain, iova, len);
1664 	__free_iova(mapping, iova, len);
1665 }
1666 
1667 static void arm_iommu_sync_single_for_cpu(struct device *dev,
1668 		dma_addr_t handle, size_t size, enum dma_data_direction dir)
1669 {
1670 	struct dma_iommu_mapping *mapping = dev->archdata.mapping;
1671 	dma_addr_t iova = handle & PAGE_MASK;
1672 	struct page *page = phys_to_page(iommu_iova_to_phys(mapping->domain, iova));
1673 	unsigned int offset = handle & ~PAGE_MASK;
1674 
1675 	if (!iova)
1676 		return;
1677 
1678 	__dma_page_dev_to_cpu(page, offset, size, dir);
1679 }
1680 
1681 static void arm_iommu_sync_single_for_device(struct device *dev,
1682 		dma_addr_t handle, size_t size, enum dma_data_direction dir)
1683 {
1684 	struct dma_iommu_mapping *mapping = dev->archdata.mapping;
1685 	dma_addr_t iova = handle & PAGE_MASK;
1686 	struct page *page = phys_to_page(iommu_iova_to_phys(mapping->domain, iova));
1687 	unsigned int offset = handle & ~PAGE_MASK;
1688 
1689 	if (!iova)
1690 		return;
1691 
1692 	__dma_page_cpu_to_dev(page, offset, size, dir);
1693 }
1694 
1695 struct dma_map_ops iommu_ops = {
1696 	.alloc		= arm_iommu_alloc_attrs,
1697 	.free		= arm_iommu_free_attrs,
1698 	.mmap		= arm_iommu_mmap_attrs,
1699 	.get_sgtable	= arm_iommu_get_sgtable,
1700 
1701 	.map_page		= arm_iommu_map_page,
1702 	.unmap_page		= arm_iommu_unmap_page,
1703 	.sync_single_for_cpu	= arm_iommu_sync_single_for_cpu,
1704 	.sync_single_for_device	= arm_iommu_sync_single_for_device,
1705 
1706 	.map_sg			= arm_iommu_map_sg,
1707 	.unmap_sg		= arm_iommu_unmap_sg,
1708 	.sync_sg_for_cpu	= arm_iommu_sync_sg_for_cpu,
1709 	.sync_sg_for_device	= arm_iommu_sync_sg_for_device,
1710 };
1711 
1712 struct dma_map_ops iommu_coherent_ops = {
1713 	.alloc		= arm_iommu_alloc_attrs,
1714 	.free		= arm_iommu_free_attrs,
1715 	.mmap		= arm_iommu_mmap_attrs,
1716 	.get_sgtable	= arm_iommu_get_sgtable,
1717 
1718 	.map_page	= arm_coherent_iommu_map_page,
1719 	.unmap_page	= arm_coherent_iommu_unmap_page,
1720 
1721 	.map_sg		= arm_coherent_iommu_map_sg,
1722 	.unmap_sg	= arm_coherent_iommu_unmap_sg,
1723 };
1724 
1725 /**
1726  * arm_iommu_create_mapping
1727  * @bus: pointer to the bus holding the client device (for IOMMU calls)
1728  * @base: start address of the valid IO address space
1729  * @size: size of the valid IO address space
1730  * @order: accuracy of the IO addresses allocations
1731  *
1732  * Creates a mapping structure which holds information about used/unused
1733  * IO address ranges, which is required to perform memory allocation and
1734  * mapping with IOMMU aware functions.
1735  *
1736  * The client device need to be attached to the mapping with
1737  * arm_iommu_attach_device function.
1738  */
1739 struct dma_iommu_mapping *
1740 arm_iommu_create_mapping(struct bus_type *bus, dma_addr_t base, size_t size,
1741 			 int order)
1742 {
1743 	unsigned int count = size >> (PAGE_SHIFT + order);
1744 	unsigned int bitmap_size = BITS_TO_LONGS(count) * sizeof(long);
1745 	struct dma_iommu_mapping *mapping;
1746 	int err = -ENOMEM;
1747 
1748 	if (!count)
1749 		return ERR_PTR(-EINVAL);
1750 
1751 	mapping = kzalloc(sizeof(struct dma_iommu_mapping), GFP_KERNEL);
1752 	if (!mapping)
1753 		goto err;
1754 
1755 	mapping->bitmap = kzalloc(bitmap_size, GFP_KERNEL);
1756 	if (!mapping->bitmap)
1757 		goto err2;
1758 
1759 	mapping->base = base;
1760 	mapping->bits = BITS_PER_BYTE * bitmap_size;
1761 	mapping->order = order;
1762 	spin_lock_init(&mapping->lock);
1763 
1764 	mapping->domain = iommu_domain_alloc(bus);
1765 	if (!mapping->domain)
1766 		goto err3;
1767 
1768 	kref_init(&mapping->kref);
1769 	return mapping;
1770 err3:
1771 	kfree(mapping->bitmap);
1772 err2:
1773 	kfree(mapping);
1774 err:
1775 	return ERR_PTR(err);
1776 }
1777 
1778 static void release_iommu_mapping(struct kref *kref)
1779 {
1780 	struct dma_iommu_mapping *mapping =
1781 		container_of(kref, struct dma_iommu_mapping, kref);
1782 
1783 	iommu_domain_free(mapping->domain);
1784 	kfree(mapping->bitmap);
1785 	kfree(mapping);
1786 }
1787 
1788 void arm_iommu_release_mapping(struct dma_iommu_mapping *mapping)
1789 {
1790 	if (mapping)
1791 		kref_put(&mapping->kref, release_iommu_mapping);
1792 }
1793 
1794 /**
1795  * arm_iommu_attach_device
1796  * @dev: valid struct device pointer
1797  * @mapping: io address space mapping structure (returned from
1798  *	arm_iommu_create_mapping)
1799  *
1800  * Attaches specified io address space mapping to the provided device,
1801  * this replaces the dma operations (dma_map_ops pointer) with the
1802  * IOMMU aware version. More than one client might be attached to
1803  * the same io address space mapping.
1804  */
1805 int arm_iommu_attach_device(struct device *dev,
1806 			    struct dma_iommu_mapping *mapping)
1807 {
1808 	int err;
1809 
1810 	err = iommu_attach_device(mapping->domain, dev);
1811 	if (err)
1812 		return err;
1813 
1814 	kref_get(&mapping->kref);
1815 	dev->archdata.mapping = mapping;
1816 	set_dma_ops(dev, &iommu_ops);
1817 
1818 	pr_debug("Attached IOMMU controller to %s device.\n", dev_name(dev));
1819 	return 0;
1820 }
1821 
1822 #endif
1823