xref: /linux/arch/arm/mm/dma-mapping.c (revision 4e1a33b105ddf201f66dcc44490c6086a25eca0b)
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/bootmem.h>
13 #include <linux/module.h>
14 #include <linux/mm.h>
15 #include <linux/genalloc.h>
16 #include <linux/gfp.h>
17 #include <linux/errno.h>
18 #include <linux/list.h>
19 #include <linux/init.h>
20 #include <linux/device.h>
21 #include <linux/dma-mapping.h>
22 #include <linux/dma-contiguous.h>
23 #include <linux/highmem.h>
24 #include <linux/memblock.h>
25 #include <linux/slab.h>
26 #include <linux/iommu.h>
27 #include <linux/io.h>
28 #include <linux/vmalloc.h>
29 #include <linux/sizes.h>
30 #include <linux/cma.h>
31 
32 #include <asm/memory.h>
33 #include <asm/highmem.h>
34 #include <asm/cacheflush.h>
35 #include <asm/tlbflush.h>
36 #include <asm/mach/arch.h>
37 #include <asm/dma-iommu.h>
38 #include <asm/mach/map.h>
39 #include <asm/system_info.h>
40 #include <asm/dma-contiguous.h>
41 
42 #include "dma.h"
43 #include "mm.h"
44 
45 struct arm_dma_alloc_args {
46 	struct device *dev;
47 	size_t size;
48 	gfp_t gfp;
49 	pgprot_t prot;
50 	const void *caller;
51 	bool want_vaddr;
52 	int coherent_flag;
53 };
54 
55 struct arm_dma_free_args {
56 	struct device *dev;
57 	size_t size;
58 	void *cpu_addr;
59 	struct page *page;
60 	bool want_vaddr;
61 };
62 
63 #define NORMAL	    0
64 #define COHERENT    1
65 
66 struct arm_dma_allocator {
67 	void *(*alloc)(struct arm_dma_alloc_args *args,
68 		       struct page **ret_page);
69 	void (*free)(struct arm_dma_free_args *args);
70 };
71 
72 struct arm_dma_buffer {
73 	struct list_head list;
74 	void *virt;
75 	struct arm_dma_allocator *allocator;
76 };
77 
78 static LIST_HEAD(arm_dma_bufs);
79 static DEFINE_SPINLOCK(arm_dma_bufs_lock);
80 
81 static struct arm_dma_buffer *arm_dma_buffer_find(void *virt)
82 {
83 	struct arm_dma_buffer *buf, *found = NULL;
84 	unsigned long flags;
85 
86 	spin_lock_irqsave(&arm_dma_bufs_lock, flags);
87 	list_for_each_entry(buf, &arm_dma_bufs, list) {
88 		if (buf->virt == virt) {
89 			list_del(&buf->list);
90 			found = buf;
91 			break;
92 		}
93 	}
94 	spin_unlock_irqrestore(&arm_dma_bufs_lock, flags);
95 	return found;
96 }
97 
98 /*
99  * The DMA API is built upon the notion of "buffer ownership".  A buffer
100  * is either exclusively owned by the CPU (and therefore may be accessed
101  * by it) or exclusively owned by the DMA device.  These helper functions
102  * represent the transitions between these two ownership states.
103  *
104  * Note, however, that on later ARMs, this notion does not work due to
105  * speculative prefetches.  We model our approach on the assumption that
106  * the CPU does do speculative prefetches, which means we clean caches
107  * before transfers and delay cache invalidation until transfer completion.
108  *
109  */
110 static void __dma_page_cpu_to_dev(struct page *, unsigned long,
111 		size_t, enum dma_data_direction);
112 static void __dma_page_dev_to_cpu(struct page *, unsigned long,
113 		size_t, enum dma_data_direction);
114 
115 /**
116  * arm_dma_map_page - map a portion of a page for streaming DMA
117  * @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
118  * @page: page that buffer resides in
119  * @offset: offset into page for start of buffer
120  * @size: size of buffer to map
121  * @dir: DMA transfer direction
122  *
123  * Ensure that any data held in the cache is appropriately discarded
124  * or written back.
125  *
126  * The device owns this memory once this call has completed.  The CPU
127  * can regain ownership by calling dma_unmap_page().
128  */
129 static dma_addr_t arm_dma_map_page(struct device *dev, struct page *page,
130 	     unsigned long offset, size_t size, enum dma_data_direction dir,
131 	     unsigned long attrs)
132 {
133 	if ((attrs & DMA_ATTR_SKIP_CPU_SYNC) == 0)
134 		__dma_page_cpu_to_dev(page, offset, size, dir);
135 	return pfn_to_dma(dev, page_to_pfn(page)) + offset;
136 }
137 
138 static dma_addr_t arm_coherent_dma_map_page(struct device *dev, struct page *page,
139 	     unsigned long offset, size_t size, enum dma_data_direction dir,
140 	     unsigned long attrs)
141 {
142 	return pfn_to_dma(dev, page_to_pfn(page)) + offset;
143 }
144 
145 /**
146  * arm_dma_unmap_page - unmap a buffer previously mapped through dma_map_page()
147  * @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
148  * @handle: DMA address of buffer
149  * @size: size of buffer (same as passed to dma_map_page)
150  * @dir: DMA transfer direction (same as passed to dma_map_page)
151  *
152  * Unmap a page streaming mode DMA translation.  The handle and size
153  * must match what was provided in the previous dma_map_page() call.
154  * All other usages are undefined.
155  *
156  * After this call, reads by the CPU to the buffer are guaranteed to see
157  * whatever the device wrote there.
158  */
159 static void arm_dma_unmap_page(struct device *dev, dma_addr_t handle,
160 		size_t size, enum dma_data_direction dir, unsigned long attrs)
161 {
162 	if ((attrs & DMA_ATTR_SKIP_CPU_SYNC) == 0)
163 		__dma_page_dev_to_cpu(pfn_to_page(dma_to_pfn(dev, handle)),
164 				      handle & ~PAGE_MASK, size, dir);
165 }
166 
167 static void arm_dma_sync_single_for_cpu(struct device *dev,
168 		dma_addr_t handle, size_t size, enum dma_data_direction dir)
169 {
170 	unsigned int offset = handle & (PAGE_SIZE - 1);
171 	struct page *page = pfn_to_page(dma_to_pfn(dev, handle-offset));
172 	__dma_page_dev_to_cpu(page, offset, size, dir);
173 }
174 
175 static void arm_dma_sync_single_for_device(struct device *dev,
176 		dma_addr_t handle, size_t size, enum dma_data_direction dir)
177 {
178 	unsigned int offset = handle & (PAGE_SIZE - 1);
179 	struct page *page = pfn_to_page(dma_to_pfn(dev, handle-offset));
180 	__dma_page_cpu_to_dev(page, offset, size, dir);
181 }
182 
183 struct dma_map_ops arm_dma_ops = {
184 	.alloc			= arm_dma_alloc,
185 	.free			= arm_dma_free,
186 	.mmap			= arm_dma_mmap,
187 	.get_sgtable		= arm_dma_get_sgtable,
188 	.map_page		= arm_dma_map_page,
189 	.unmap_page		= arm_dma_unmap_page,
190 	.map_sg			= arm_dma_map_sg,
191 	.unmap_sg		= arm_dma_unmap_sg,
192 	.sync_single_for_cpu	= arm_dma_sync_single_for_cpu,
193 	.sync_single_for_device	= arm_dma_sync_single_for_device,
194 	.sync_sg_for_cpu	= arm_dma_sync_sg_for_cpu,
195 	.sync_sg_for_device	= arm_dma_sync_sg_for_device,
196 };
197 EXPORT_SYMBOL(arm_dma_ops);
198 
199 static void *arm_coherent_dma_alloc(struct device *dev, size_t size,
200 	dma_addr_t *handle, gfp_t gfp, unsigned long attrs);
201 static void arm_coherent_dma_free(struct device *dev, size_t size, void *cpu_addr,
202 				  dma_addr_t handle, unsigned long attrs);
203 static int arm_coherent_dma_mmap(struct device *dev, struct vm_area_struct *vma,
204 		 void *cpu_addr, dma_addr_t dma_addr, size_t size,
205 		 unsigned long attrs);
206 
207 struct dma_map_ops arm_coherent_dma_ops = {
208 	.alloc			= arm_coherent_dma_alloc,
209 	.free			= arm_coherent_dma_free,
210 	.mmap			= arm_coherent_dma_mmap,
211 	.get_sgtable		= arm_dma_get_sgtable,
212 	.map_page		= arm_coherent_dma_map_page,
213 	.map_sg			= arm_dma_map_sg,
214 };
215 EXPORT_SYMBOL(arm_coherent_dma_ops);
216 
217 static int __dma_supported(struct device *dev, u64 mask, bool warn)
218 {
219 	unsigned long max_dma_pfn;
220 
221 	/*
222 	 * If the mask allows for more memory than we can address,
223 	 * and we actually have that much memory, then we must
224 	 * indicate that DMA to this device is not supported.
225 	 */
226 	if (sizeof(mask) != sizeof(dma_addr_t) &&
227 	    mask > (dma_addr_t)~0 &&
228 	    dma_to_pfn(dev, ~0) < max_pfn - 1) {
229 		if (warn) {
230 			dev_warn(dev, "Coherent DMA mask %#llx is larger than dma_addr_t allows\n",
231 				 mask);
232 			dev_warn(dev, "Driver did not use or check the return value from dma_set_coherent_mask()?\n");
233 		}
234 		return 0;
235 	}
236 
237 	max_dma_pfn = min(max_pfn, arm_dma_pfn_limit);
238 
239 	/*
240 	 * Translate the device's DMA mask to a PFN limit.  This
241 	 * PFN number includes the page which we can DMA to.
242 	 */
243 	if (dma_to_pfn(dev, mask) < max_dma_pfn) {
244 		if (warn)
245 			dev_warn(dev, "Coherent DMA mask %#llx (pfn %#lx-%#lx) covers a smaller range of system memory than the DMA zone pfn 0x0-%#lx\n",
246 				 mask,
247 				 dma_to_pfn(dev, 0), dma_to_pfn(dev, mask) + 1,
248 				 max_dma_pfn + 1);
249 		return 0;
250 	}
251 
252 	return 1;
253 }
254 
255 static u64 get_coherent_dma_mask(struct device *dev)
256 {
257 	u64 mask = (u64)DMA_BIT_MASK(32);
258 
259 	if (dev) {
260 		mask = dev->coherent_dma_mask;
261 
262 		/*
263 		 * Sanity check the DMA mask - it must be non-zero, and
264 		 * must be able to be satisfied by a DMA allocation.
265 		 */
266 		if (mask == 0) {
267 			dev_warn(dev, "coherent DMA mask is unset\n");
268 			return 0;
269 		}
270 
271 		if (!__dma_supported(dev, mask, true))
272 			return 0;
273 	}
274 
275 	return mask;
276 }
277 
278 static void __dma_clear_buffer(struct page *page, size_t size, int coherent_flag)
279 {
280 	/*
281 	 * Ensure that the allocated pages are zeroed, and that any data
282 	 * lurking in the kernel direct-mapped region is invalidated.
283 	 */
284 	if (PageHighMem(page)) {
285 		phys_addr_t base = __pfn_to_phys(page_to_pfn(page));
286 		phys_addr_t end = base + size;
287 		while (size > 0) {
288 			void *ptr = kmap_atomic(page);
289 			memset(ptr, 0, PAGE_SIZE);
290 			if (coherent_flag != COHERENT)
291 				dmac_flush_range(ptr, ptr + PAGE_SIZE);
292 			kunmap_atomic(ptr);
293 			page++;
294 			size -= PAGE_SIZE;
295 		}
296 		if (coherent_flag != COHERENT)
297 			outer_flush_range(base, end);
298 	} else {
299 		void *ptr = page_address(page);
300 		memset(ptr, 0, size);
301 		if (coherent_flag != COHERENT) {
302 			dmac_flush_range(ptr, ptr + size);
303 			outer_flush_range(__pa(ptr), __pa(ptr) + size);
304 		}
305 	}
306 }
307 
308 /*
309  * Allocate a DMA buffer for 'dev' of size 'size' using the
310  * specified gfp mask.  Note that 'size' must be page aligned.
311  */
312 static struct page *__dma_alloc_buffer(struct device *dev, size_t size,
313 				       gfp_t gfp, int coherent_flag)
314 {
315 	unsigned long order = get_order(size);
316 	struct page *page, *p, *e;
317 
318 	page = alloc_pages(gfp, order);
319 	if (!page)
320 		return NULL;
321 
322 	/*
323 	 * Now split the huge page and free the excess pages
324 	 */
325 	split_page(page, order);
326 	for (p = page + (size >> PAGE_SHIFT), e = page + (1 << order); p < e; p++)
327 		__free_page(p);
328 
329 	__dma_clear_buffer(page, size, coherent_flag);
330 
331 	return page;
332 }
333 
334 /*
335  * Free a DMA buffer.  'size' must be page aligned.
336  */
337 static void __dma_free_buffer(struct page *page, size_t size)
338 {
339 	struct page *e = page + (size >> PAGE_SHIFT);
340 
341 	while (page < e) {
342 		__free_page(page);
343 		page++;
344 	}
345 }
346 
347 #ifdef CONFIG_MMU
348 
349 static void *__alloc_from_contiguous(struct device *dev, size_t size,
350 				     pgprot_t prot, struct page **ret_page,
351 				     const void *caller, bool want_vaddr,
352 				     int coherent_flag, gfp_t gfp);
353 
354 static void *__alloc_remap_buffer(struct device *dev, size_t size, gfp_t gfp,
355 				 pgprot_t prot, struct page **ret_page,
356 				 const void *caller, bool want_vaddr);
357 
358 static void *
359 __dma_alloc_remap(struct page *page, size_t size, gfp_t gfp, pgprot_t prot,
360 	const void *caller)
361 {
362 	/*
363 	 * DMA allocation can be mapped to user space, so lets
364 	 * set VM_USERMAP flags too.
365 	 */
366 	return dma_common_contiguous_remap(page, size,
367 			VM_ARM_DMA_CONSISTENT | VM_USERMAP,
368 			prot, caller);
369 }
370 
371 static void __dma_free_remap(void *cpu_addr, size_t size)
372 {
373 	dma_common_free_remap(cpu_addr, size,
374 			VM_ARM_DMA_CONSISTENT | VM_USERMAP);
375 }
376 
377 #define DEFAULT_DMA_COHERENT_POOL_SIZE	SZ_256K
378 static struct gen_pool *atomic_pool;
379 
380 static size_t atomic_pool_size = DEFAULT_DMA_COHERENT_POOL_SIZE;
381 
382 static int __init early_coherent_pool(char *p)
383 {
384 	atomic_pool_size = memparse(p, &p);
385 	return 0;
386 }
387 early_param("coherent_pool", early_coherent_pool);
388 
389 void __init init_dma_coherent_pool_size(unsigned long size)
390 {
391 	/*
392 	 * Catch any attempt to set the pool size too late.
393 	 */
394 	BUG_ON(atomic_pool);
395 
396 	/*
397 	 * Set architecture specific coherent pool size only if
398 	 * it has not been changed by kernel command line parameter.
399 	 */
400 	if (atomic_pool_size == DEFAULT_DMA_COHERENT_POOL_SIZE)
401 		atomic_pool_size = size;
402 }
403 
404 /*
405  * Initialise the coherent pool for atomic allocations.
406  */
407 static int __init atomic_pool_init(void)
408 {
409 	pgprot_t prot = pgprot_dmacoherent(PAGE_KERNEL);
410 	gfp_t gfp = GFP_KERNEL | GFP_DMA;
411 	struct page *page;
412 	void *ptr;
413 
414 	atomic_pool = gen_pool_create(PAGE_SHIFT, -1);
415 	if (!atomic_pool)
416 		goto out;
417 	/*
418 	 * The atomic pool is only used for non-coherent allocations
419 	 * so we must pass NORMAL for coherent_flag.
420 	 */
421 	if (dev_get_cma_area(NULL))
422 		ptr = __alloc_from_contiguous(NULL, atomic_pool_size, prot,
423 				      &page, atomic_pool_init, true, NORMAL,
424 				      GFP_KERNEL);
425 	else
426 		ptr = __alloc_remap_buffer(NULL, atomic_pool_size, gfp, prot,
427 					   &page, atomic_pool_init, true);
428 	if (ptr) {
429 		int ret;
430 
431 		ret = gen_pool_add_virt(atomic_pool, (unsigned long)ptr,
432 					page_to_phys(page),
433 					atomic_pool_size, -1);
434 		if (ret)
435 			goto destroy_genpool;
436 
437 		gen_pool_set_algo(atomic_pool,
438 				gen_pool_first_fit_order_align,
439 				(void *)PAGE_SHIFT);
440 		pr_info("DMA: preallocated %zu KiB pool for atomic coherent allocations\n",
441 		       atomic_pool_size / 1024);
442 		return 0;
443 	}
444 
445 destroy_genpool:
446 	gen_pool_destroy(atomic_pool);
447 	atomic_pool = NULL;
448 out:
449 	pr_err("DMA: failed to allocate %zu KiB pool for atomic coherent allocation\n",
450 	       atomic_pool_size / 1024);
451 	return -ENOMEM;
452 }
453 /*
454  * CMA is activated by core_initcall, so we must be called after it.
455  */
456 postcore_initcall(atomic_pool_init);
457 
458 struct dma_contig_early_reserve {
459 	phys_addr_t base;
460 	unsigned long size;
461 };
462 
463 static struct dma_contig_early_reserve dma_mmu_remap[MAX_CMA_AREAS] __initdata;
464 
465 static int dma_mmu_remap_num __initdata;
466 
467 void __init dma_contiguous_early_fixup(phys_addr_t base, unsigned long size)
468 {
469 	dma_mmu_remap[dma_mmu_remap_num].base = base;
470 	dma_mmu_remap[dma_mmu_remap_num].size = size;
471 	dma_mmu_remap_num++;
472 }
473 
474 void __init dma_contiguous_remap(void)
475 {
476 	int i;
477 	for (i = 0; i < dma_mmu_remap_num; i++) {
478 		phys_addr_t start = dma_mmu_remap[i].base;
479 		phys_addr_t end = start + dma_mmu_remap[i].size;
480 		struct map_desc map;
481 		unsigned long addr;
482 
483 		if (end > arm_lowmem_limit)
484 			end = arm_lowmem_limit;
485 		if (start >= end)
486 			continue;
487 
488 		map.pfn = __phys_to_pfn(start);
489 		map.virtual = __phys_to_virt(start);
490 		map.length = end - start;
491 		map.type = MT_MEMORY_DMA_READY;
492 
493 		/*
494 		 * Clear previous low-memory mapping to ensure that the
495 		 * TLB does not see any conflicting entries, then flush
496 		 * the TLB of the old entries before creating new mappings.
497 		 *
498 		 * This ensures that any speculatively loaded TLB entries
499 		 * (even though they may be rare) can not cause any problems,
500 		 * and ensures that this code is architecturally compliant.
501 		 */
502 		for (addr = __phys_to_virt(start); addr < __phys_to_virt(end);
503 		     addr += PMD_SIZE)
504 			pmd_clear(pmd_off_k(addr));
505 
506 		flush_tlb_kernel_range(__phys_to_virt(start),
507 				       __phys_to_virt(end));
508 
509 		iotable_init(&map, 1);
510 	}
511 }
512 
513 static int __dma_update_pte(pte_t *pte, pgtable_t token, unsigned long addr,
514 			    void *data)
515 {
516 	struct page *page = virt_to_page(addr);
517 	pgprot_t prot = *(pgprot_t *)data;
518 
519 	set_pte_ext(pte, mk_pte(page, prot), 0);
520 	return 0;
521 }
522 
523 static void __dma_remap(struct page *page, size_t size, pgprot_t prot)
524 {
525 	unsigned long start = (unsigned long) page_address(page);
526 	unsigned end = start + size;
527 
528 	apply_to_page_range(&init_mm, start, size, __dma_update_pte, &prot);
529 	flush_tlb_kernel_range(start, end);
530 }
531 
532 static void *__alloc_remap_buffer(struct device *dev, size_t size, gfp_t gfp,
533 				 pgprot_t prot, struct page **ret_page,
534 				 const void *caller, bool want_vaddr)
535 {
536 	struct page *page;
537 	void *ptr = NULL;
538 	/*
539 	 * __alloc_remap_buffer is only called when the device is
540 	 * non-coherent
541 	 */
542 	page = __dma_alloc_buffer(dev, size, gfp, NORMAL);
543 	if (!page)
544 		return NULL;
545 	if (!want_vaddr)
546 		goto out;
547 
548 	ptr = __dma_alloc_remap(page, size, gfp, prot, caller);
549 	if (!ptr) {
550 		__dma_free_buffer(page, size);
551 		return NULL;
552 	}
553 
554  out:
555 	*ret_page = page;
556 	return ptr;
557 }
558 
559 static void *__alloc_from_pool(size_t size, struct page **ret_page)
560 {
561 	unsigned long val;
562 	void *ptr = NULL;
563 
564 	if (!atomic_pool) {
565 		WARN(1, "coherent pool not initialised!\n");
566 		return NULL;
567 	}
568 
569 	val = gen_pool_alloc(atomic_pool, size);
570 	if (val) {
571 		phys_addr_t phys = gen_pool_virt_to_phys(atomic_pool, val);
572 
573 		*ret_page = phys_to_page(phys);
574 		ptr = (void *)val;
575 	}
576 
577 	return ptr;
578 }
579 
580 static bool __in_atomic_pool(void *start, size_t size)
581 {
582 	return addr_in_gen_pool(atomic_pool, (unsigned long)start, size);
583 }
584 
585 static int __free_from_pool(void *start, size_t size)
586 {
587 	if (!__in_atomic_pool(start, size))
588 		return 0;
589 
590 	gen_pool_free(atomic_pool, (unsigned long)start, size);
591 
592 	return 1;
593 }
594 
595 static void *__alloc_from_contiguous(struct device *dev, size_t size,
596 				     pgprot_t prot, struct page **ret_page,
597 				     const void *caller, bool want_vaddr,
598 				     int coherent_flag, gfp_t gfp)
599 {
600 	unsigned long order = get_order(size);
601 	size_t count = size >> PAGE_SHIFT;
602 	struct page *page;
603 	void *ptr = NULL;
604 
605 	page = dma_alloc_from_contiguous(dev, count, order, gfp);
606 	if (!page)
607 		return NULL;
608 
609 	__dma_clear_buffer(page, size, coherent_flag);
610 
611 	if (!want_vaddr)
612 		goto out;
613 
614 	if (PageHighMem(page)) {
615 		ptr = __dma_alloc_remap(page, size, GFP_KERNEL, prot, caller);
616 		if (!ptr) {
617 			dma_release_from_contiguous(dev, page, count);
618 			return NULL;
619 		}
620 	} else {
621 		__dma_remap(page, size, prot);
622 		ptr = page_address(page);
623 	}
624 
625  out:
626 	*ret_page = page;
627 	return ptr;
628 }
629 
630 static void __free_from_contiguous(struct device *dev, struct page *page,
631 				   void *cpu_addr, size_t size, bool want_vaddr)
632 {
633 	if (want_vaddr) {
634 		if (PageHighMem(page))
635 			__dma_free_remap(cpu_addr, size);
636 		else
637 			__dma_remap(page, size, PAGE_KERNEL);
638 	}
639 	dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT);
640 }
641 
642 static inline pgprot_t __get_dma_pgprot(unsigned long attrs, pgprot_t prot)
643 {
644 	prot = (attrs & DMA_ATTR_WRITE_COMBINE) ?
645 			pgprot_writecombine(prot) :
646 			pgprot_dmacoherent(prot);
647 	return prot;
648 }
649 
650 #define nommu() 0
651 
652 #else	/* !CONFIG_MMU */
653 
654 #define nommu() 1
655 
656 #define __get_dma_pgprot(attrs, prot)				__pgprot(0)
657 #define __alloc_remap_buffer(dev, size, gfp, prot, ret, c, wv)	NULL
658 #define __alloc_from_pool(size, ret_page)			NULL
659 #define __alloc_from_contiguous(dev, size, prot, ret, c, wv, coherent_flag, gfp)	NULL
660 #define __free_from_pool(cpu_addr, size)			do { } while (0)
661 #define __free_from_contiguous(dev, page, cpu_addr, size, wv)	do { } while (0)
662 #define __dma_free_remap(cpu_addr, size)			do { } while (0)
663 
664 #endif	/* CONFIG_MMU */
665 
666 static void *__alloc_simple_buffer(struct device *dev, size_t size, gfp_t gfp,
667 				   struct page **ret_page)
668 {
669 	struct page *page;
670 	/* __alloc_simple_buffer is only called when the device is coherent */
671 	page = __dma_alloc_buffer(dev, size, gfp, COHERENT);
672 	if (!page)
673 		return NULL;
674 
675 	*ret_page = page;
676 	return page_address(page);
677 }
678 
679 static void *simple_allocator_alloc(struct arm_dma_alloc_args *args,
680 				    struct page **ret_page)
681 {
682 	return __alloc_simple_buffer(args->dev, args->size, args->gfp,
683 				     ret_page);
684 }
685 
686 static void simple_allocator_free(struct arm_dma_free_args *args)
687 {
688 	__dma_free_buffer(args->page, args->size);
689 }
690 
691 static struct arm_dma_allocator simple_allocator = {
692 	.alloc = simple_allocator_alloc,
693 	.free = simple_allocator_free,
694 };
695 
696 static void *cma_allocator_alloc(struct arm_dma_alloc_args *args,
697 				 struct page **ret_page)
698 {
699 	return __alloc_from_contiguous(args->dev, args->size, args->prot,
700 				       ret_page, args->caller,
701 				       args->want_vaddr, args->coherent_flag,
702 				       args->gfp);
703 }
704 
705 static void cma_allocator_free(struct arm_dma_free_args *args)
706 {
707 	__free_from_contiguous(args->dev, args->page, args->cpu_addr,
708 			       args->size, args->want_vaddr);
709 }
710 
711 static struct arm_dma_allocator cma_allocator = {
712 	.alloc = cma_allocator_alloc,
713 	.free = cma_allocator_free,
714 };
715 
716 static void *pool_allocator_alloc(struct arm_dma_alloc_args *args,
717 				  struct page **ret_page)
718 {
719 	return __alloc_from_pool(args->size, ret_page);
720 }
721 
722 static void pool_allocator_free(struct arm_dma_free_args *args)
723 {
724 	__free_from_pool(args->cpu_addr, args->size);
725 }
726 
727 static struct arm_dma_allocator pool_allocator = {
728 	.alloc = pool_allocator_alloc,
729 	.free = pool_allocator_free,
730 };
731 
732 static void *remap_allocator_alloc(struct arm_dma_alloc_args *args,
733 				   struct page **ret_page)
734 {
735 	return __alloc_remap_buffer(args->dev, args->size, args->gfp,
736 				    args->prot, ret_page, args->caller,
737 				    args->want_vaddr);
738 }
739 
740 static void remap_allocator_free(struct arm_dma_free_args *args)
741 {
742 	if (args->want_vaddr)
743 		__dma_free_remap(args->cpu_addr, args->size);
744 
745 	__dma_free_buffer(args->page, args->size);
746 }
747 
748 static struct arm_dma_allocator remap_allocator = {
749 	.alloc = remap_allocator_alloc,
750 	.free = remap_allocator_free,
751 };
752 
753 static void *__dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
754 			 gfp_t gfp, pgprot_t prot, bool is_coherent,
755 			 unsigned long attrs, const void *caller)
756 {
757 	u64 mask = get_coherent_dma_mask(dev);
758 	struct page *page = NULL;
759 	void *addr;
760 	bool allowblock, cma;
761 	struct arm_dma_buffer *buf;
762 	struct arm_dma_alloc_args args = {
763 		.dev = dev,
764 		.size = PAGE_ALIGN(size),
765 		.gfp = gfp,
766 		.prot = prot,
767 		.caller = caller,
768 		.want_vaddr = ((attrs & DMA_ATTR_NO_KERNEL_MAPPING) == 0),
769 		.coherent_flag = is_coherent ? COHERENT : NORMAL,
770 	};
771 
772 #ifdef CONFIG_DMA_API_DEBUG
773 	u64 limit = (mask + 1) & ~mask;
774 	if (limit && size >= limit) {
775 		dev_warn(dev, "coherent allocation too big (requested %#x mask %#llx)\n",
776 			size, mask);
777 		return NULL;
778 	}
779 #endif
780 
781 	if (!mask)
782 		return NULL;
783 
784 	buf = kzalloc(sizeof(*buf),
785 		      gfp & ~(__GFP_DMA | __GFP_DMA32 | __GFP_HIGHMEM));
786 	if (!buf)
787 		return NULL;
788 
789 	if (mask < 0xffffffffULL)
790 		gfp |= GFP_DMA;
791 
792 	/*
793 	 * Following is a work-around (a.k.a. hack) to prevent pages
794 	 * with __GFP_COMP being passed to split_page() which cannot
795 	 * handle them.  The real problem is that this flag probably
796 	 * should be 0 on ARM as it is not supported on this
797 	 * platform; see CONFIG_HUGETLBFS.
798 	 */
799 	gfp &= ~(__GFP_COMP);
800 	args.gfp = gfp;
801 
802 	*handle = DMA_ERROR_CODE;
803 	allowblock = gfpflags_allow_blocking(gfp);
804 	cma = allowblock ? dev_get_cma_area(dev) : false;
805 
806 	if (cma)
807 		buf->allocator = &cma_allocator;
808 	else if (nommu() || is_coherent)
809 		buf->allocator = &simple_allocator;
810 	else if (allowblock)
811 		buf->allocator = &remap_allocator;
812 	else
813 		buf->allocator = &pool_allocator;
814 
815 	addr = buf->allocator->alloc(&args, &page);
816 
817 	if (page) {
818 		unsigned long flags;
819 
820 		*handle = pfn_to_dma(dev, page_to_pfn(page));
821 		buf->virt = args.want_vaddr ? addr : page;
822 
823 		spin_lock_irqsave(&arm_dma_bufs_lock, flags);
824 		list_add(&buf->list, &arm_dma_bufs);
825 		spin_unlock_irqrestore(&arm_dma_bufs_lock, flags);
826 	} else {
827 		kfree(buf);
828 	}
829 
830 	return args.want_vaddr ? addr : page;
831 }
832 
833 /*
834  * Allocate DMA-coherent memory space and return both the kernel remapped
835  * virtual and bus address for that space.
836  */
837 void *arm_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
838 		    gfp_t gfp, unsigned long attrs)
839 {
840 	pgprot_t prot = __get_dma_pgprot(attrs, PAGE_KERNEL);
841 
842 	return __dma_alloc(dev, size, handle, gfp, prot, false,
843 			   attrs, __builtin_return_address(0));
844 }
845 
846 static void *arm_coherent_dma_alloc(struct device *dev, size_t size,
847 	dma_addr_t *handle, gfp_t gfp, unsigned long attrs)
848 {
849 	return __dma_alloc(dev, size, handle, gfp, PAGE_KERNEL, true,
850 			   attrs, __builtin_return_address(0));
851 }
852 
853 static int __arm_dma_mmap(struct device *dev, struct vm_area_struct *vma,
854 		 void *cpu_addr, dma_addr_t dma_addr, size_t size,
855 		 unsigned long attrs)
856 {
857 	int ret = -ENXIO;
858 #ifdef CONFIG_MMU
859 	unsigned long nr_vma_pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
860 	unsigned long nr_pages = PAGE_ALIGN(size) >> PAGE_SHIFT;
861 	unsigned long pfn = dma_to_pfn(dev, dma_addr);
862 	unsigned long off = vma->vm_pgoff;
863 
864 	if (dma_mmap_from_coherent(dev, vma, cpu_addr, size, &ret))
865 		return ret;
866 
867 	if (off < nr_pages && nr_vma_pages <= (nr_pages - off)) {
868 		ret = remap_pfn_range(vma, vma->vm_start,
869 				      pfn + off,
870 				      vma->vm_end - vma->vm_start,
871 				      vma->vm_page_prot);
872 	}
873 #endif	/* CONFIG_MMU */
874 
875 	return ret;
876 }
877 
878 /*
879  * Create userspace mapping for the DMA-coherent memory.
880  */
881 static int arm_coherent_dma_mmap(struct device *dev, struct vm_area_struct *vma,
882 		 void *cpu_addr, dma_addr_t dma_addr, size_t size,
883 		 unsigned long attrs)
884 {
885 	return __arm_dma_mmap(dev, vma, cpu_addr, dma_addr, size, attrs);
886 }
887 
888 int arm_dma_mmap(struct device *dev, struct vm_area_struct *vma,
889 		 void *cpu_addr, dma_addr_t dma_addr, size_t size,
890 		 unsigned long attrs)
891 {
892 #ifdef CONFIG_MMU
893 	vma->vm_page_prot = __get_dma_pgprot(attrs, vma->vm_page_prot);
894 #endif	/* CONFIG_MMU */
895 	return __arm_dma_mmap(dev, vma, cpu_addr, dma_addr, size, attrs);
896 }
897 
898 /*
899  * Free a buffer as defined by the above mapping.
900  */
901 static void __arm_dma_free(struct device *dev, size_t size, void *cpu_addr,
902 			   dma_addr_t handle, unsigned long attrs,
903 			   bool is_coherent)
904 {
905 	struct page *page = pfn_to_page(dma_to_pfn(dev, handle));
906 	struct arm_dma_buffer *buf;
907 	struct arm_dma_free_args args = {
908 		.dev = dev,
909 		.size = PAGE_ALIGN(size),
910 		.cpu_addr = cpu_addr,
911 		.page = page,
912 		.want_vaddr = ((attrs & DMA_ATTR_NO_KERNEL_MAPPING) == 0),
913 	};
914 
915 	buf = arm_dma_buffer_find(cpu_addr);
916 	if (WARN(!buf, "Freeing invalid buffer %p\n", cpu_addr))
917 		return;
918 
919 	buf->allocator->free(&args);
920 	kfree(buf);
921 }
922 
923 void arm_dma_free(struct device *dev, size_t size, void *cpu_addr,
924 		  dma_addr_t handle, unsigned long attrs)
925 {
926 	__arm_dma_free(dev, size, cpu_addr, handle, attrs, false);
927 }
928 
929 static void arm_coherent_dma_free(struct device *dev, size_t size, void *cpu_addr,
930 				  dma_addr_t handle, unsigned long attrs)
931 {
932 	__arm_dma_free(dev, size, cpu_addr, handle, attrs, true);
933 }
934 
935 int arm_dma_get_sgtable(struct device *dev, struct sg_table *sgt,
936 		 void *cpu_addr, dma_addr_t handle, size_t size,
937 		 unsigned long attrs)
938 {
939 	struct page *page = pfn_to_page(dma_to_pfn(dev, handle));
940 	int ret;
941 
942 	ret = sg_alloc_table(sgt, 1, GFP_KERNEL);
943 	if (unlikely(ret))
944 		return ret;
945 
946 	sg_set_page(sgt->sgl, page, PAGE_ALIGN(size), 0);
947 	return 0;
948 }
949 
950 static void dma_cache_maint_page(struct page *page, unsigned long offset,
951 	size_t size, enum dma_data_direction dir,
952 	void (*op)(const void *, size_t, int))
953 {
954 	unsigned long pfn;
955 	size_t left = size;
956 
957 	pfn = page_to_pfn(page) + offset / PAGE_SIZE;
958 	offset %= PAGE_SIZE;
959 
960 	/*
961 	 * A single sg entry may refer to multiple physically contiguous
962 	 * pages.  But we still need to process highmem pages individually.
963 	 * If highmem is not configured then the bulk of this loop gets
964 	 * optimized out.
965 	 */
966 	do {
967 		size_t len = left;
968 		void *vaddr;
969 
970 		page = pfn_to_page(pfn);
971 
972 		if (PageHighMem(page)) {
973 			if (len + offset > PAGE_SIZE)
974 				len = PAGE_SIZE - offset;
975 
976 			if (cache_is_vipt_nonaliasing()) {
977 				vaddr = kmap_atomic(page);
978 				op(vaddr + offset, len, dir);
979 				kunmap_atomic(vaddr);
980 			} else {
981 				vaddr = kmap_high_get(page);
982 				if (vaddr) {
983 					op(vaddr + offset, len, dir);
984 					kunmap_high(page);
985 				}
986 			}
987 		} else {
988 			vaddr = page_address(page) + offset;
989 			op(vaddr, len, dir);
990 		}
991 		offset = 0;
992 		pfn++;
993 		left -= len;
994 	} while (left);
995 }
996 
997 /*
998  * Make an area consistent for devices.
999  * Note: Drivers should NOT use this function directly, as it will break
1000  * platforms with CONFIG_DMABOUNCE.
1001  * Use the driver DMA support - see dma-mapping.h (dma_sync_*)
1002  */
1003 static void __dma_page_cpu_to_dev(struct page *page, unsigned long off,
1004 	size_t size, enum dma_data_direction dir)
1005 {
1006 	phys_addr_t paddr;
1007 
1008 	dma_cache_maint_page(page, off, size, dir, dmac_map_area);
1009 
1010 	paddr = page_to_phys(page) + off;
1011 	if (dir == DMA_FROM_DEVICE) {
1012 		outer_inv_range(paddr, paddr + size);
1013 	} else {
1014 		outer_clean_range(paddr, paddr + size);
1015 	}
1016 	/* FIXME: non-speculating: flush on bidirectional mappings? */
1017 }
1018 
1019 static void __dma_page_dev_to_cpu(struct page *page, unsigned long off,
1020 	size_t size, enum dma_data_direction dir)
1021 {
1022 	phys_addr_t paddr = page_to_phys(page) + off;
1023 
1024 	/* FIXME: non-speculating: not required */
1025 	/* in any case, don't bother invalidating if DMA to device */
1026 	if (dir != DMA_TO_DEVICE) {
1027 		outer_inv_range(paddr, paddr + size);
1028 
1029 		dma_cache_maint_page(page, off, size, dir, dmac_unmap_area);
1030 	}
1031 
1032 	/*
1033 	 * Mark the D-cache clean for these pages to avoid extra flushing.
1034 	 */
1035 	if (dir != DMA_TO_DEVICE && size >= PAGE_SIZE) {
1036 		unsigned long pfn;
1037 		size_t left = size;
1038 
1039 		pfn = page_to_pfn(page) + off / PAGE_SIZE;
1040 		off %= PAGE_SIZE;
1041 		if (off) {
1042 			pfn++;
1043 			left -= PAGE_SIZE - off;
1044 		}
1045 		while (left >= PAGE_SIZE) {
1046 			page = pfn_to_page(pfn++);
1047 			set_bit(PG_dcache_clean, &page->flags);
1048 			left -= PAGE_SIZE;
1049 		}
1050 	}
1051 }
1052 
1053 /**
1054  * arm_dma_map_sg - map a set of SG buffers for streaming mode DMA
1055  * @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
1056  * @sg: list of buffers
1057  * @nents: number of buffers to map
1058  * @dir: DMA transfer direction
1059  *
1060  * Map a set of buffers described by scatterlist in streaming mode for DMA.
1061  * This is the scatter-gather version of the dma_map_single interface.
1062  * Here the scatter gather list elements are each tagged with the
1063  * appropriate dma address and length.  They are obtained via
1064  * sg_dma_{address,length}.
1065  *
1066  * Device ownership issues as mentioned for dma_map_single are the same
1067  * here.
1068  */
1069 int arm_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
1070 		enum dma_data_direction dir, unsigned long attrs)
1071 {
1072 	struct dma_map_ops *ops = get_dma_ops(dev);
1073 	struct scatterlist *s;
1074 	int i, j;
1075 
1076 	for_each_sg(sg, s, nents, i) {
1077 #ifdef CONFIG_NEED_SG_DMA_LENGTH
1078 		s->dma_length = s->length;
1079 #endif
1080 		s->dma_address = ops->map_page(dev, sg_page(s), s->offset,
1081 						s->length, dir, attrs);
1082 		if (dma_mapping_error(dev, s->dma_address))
1083 			goto bad_mapping;
1084 	}
1085 	return nents;
1086 
1087  bad_mapping:
1088 	for_each_sg(sg, s, i, j)
1089 		ops->unmap_page(dev, sg_dma_address(s), sg_dma_len(s), dir, attrs);
1090 	return 0;
1091 }
1092 
1093 /**
1094  * arm_dma_unmap_sg - unmap a set of SG buffers mapped by dma_map_sg
1095  * @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
1096  * @sg: list of buffers
1097  * @nents: number of buffers to unmap (same as was passed to dma_map_sg)
1098  * @dir: DMA transfer direction (same as was passed to dma_map_sg)
1099  *
1100  * Unmap a set of streaming mode DMA translations.  Again, CPU access
1101  * rules concerning calls here are the same as for dma_unmap_single().
1102  */
1103 void arm_dma_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
1104 		enum dma_data_direction dir, unsigned long attrs)
1105 {
1106 	struct dma_map_ops *ops = get_dma_ops(dev);
1107 	struct scatterlist *s;
1108 
1109 	int i;
1110 
1111 	for_each_sg(sg, s, nents, i)
1112 		ops->unmap_page(dev, sg_dma_address(s), sg_dma_len(s), dir, attrs);
1113 }
1114 
1115 /**
1116  * arm_dma_sync_sg_for_cpu
1117  * @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
1118  * @sg: list of buffers
1119  * @nents: number of buffers to map (returned from dma_map_sg)
1120  * @dir: DMA transfer direction (same as was passed to dma_map_sg)
1121  */
1122 void arm_dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
1123 			int nents, enum dma_data_direction dir)
1124 {
1125 	struct dma_map_ops *ops = get_dma_ops(dev);
1126 	struct scatterlist *s;
1127 	int i;
1128 
1129 	for_each_sg(sg, s, nents, i)
1130 		ops->sync_single_for_cpu(dev, sg_dma_address(s), s->length,
1131 					 dir);
1132 }
1133 
1134 /**
1135  * arm_dma_sync_sg_for_device
1136  * @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
1137  * @sg: list of buffers
1138  * @nents: number of buffers to map (returned from dma_map_sg)
1139  * @dir: DMA transfer direction (same as was passed to dma_map_sg)
1140  */
1141 void arm_dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
1142 			int nents, enum dma_data_direction dir)
1143 {
1144 	struct dma_map_ops *ops = get_dma_ops(dev);
1145 	struct scatterlist *s;
1146 	int i;
1147 
1148 	for_each_sg(sg, s, nents, i)
1149 		ops->sync_single_for_device(dev, sg_dma_address(s), s->length,
1150 					    dir);
1151 }
1152 
1153 /*
1154  * Return whether the given device DMA address mask can be supported
1155  * properly.  For example, if your device can only drive the low 24-bits
1156  * during bus mastering, then you would pass 0x00ffffff as the mask
1157  * to this function.
1158  */
1159 int dma_supported(struct device *dev, u64 mask)
1160 {
1161 	return __dma_supported(dev, mask, false);
1162 }
1163 EXPORT_SYMBOL(dma_supported);
1164 
1165 #define PREALLOC_DMA_DEBUG_ENTRIES	4096
1166 
1167 static int __init dma_debug_do_init(void)
1168 {
1169 	dma_debug_init(PREALLOC_DMA_DEBUG_ENTRIES);
1170 	return 0;
1171 }
1172 core_initcall(dma_debug_do_init);
1173 
1174 #ifdef CONFIG_ARM_DMA_USE_IOMMU
1175 
1176 static int __dma_info_to_prot(enum dma_data_direction dir, unsigned long attrs)
1177 {
1178 	int prot = 0;
1179 
1180 	if (attrs & DMA_ATTR_PRIVILEGED)
1181 		prot |= IOMMU_PRIV;
1182 
1183 	switch (dir) {
1184 	case DMA_BIDIRECTIONAL:
1185 		return prot | IOMMU_READ | IOMMU_WRITE;
1186 	case DMA_TO_DEVICE:
1187 		return prot | IOMMU_READ;
1188 	case DMA_FROM_DEVICE:
1189 		return prot | IOMMU_WRITE;
1190 	default:
1191 		return prot;
1192 	}
1193 }
1194 
1195 /* IOMMU */
1196 
1197 static int extend_iommu_mapping(struct dma_iommu_mapping *mapping);
1198 
1199 static inline dma_addr_t __alloc_iova(struct dma_iommu_mapping *mapping,
1200 				      size_t size)
1201 {
1202 	unsigned int order = get_order(size);
1203 	unsigned int align = 0;
1204 	unsigned int count, start;
1205 	size_t mapping_size = mapping->bits << PAGE_SHIFT;
1206 	unsigned long flags;
1207 	dma_addr_t iova;
1208 	int i;
1209 
1210 	if (order > CONFIG_ARM_DMA_IOMMU_ALIGNMENT)
1211 		order = CONFIG_ARM_DMA_IOMMU_ALIGNMENT;
1212 
1213 	count = PAGE_ALIGN(size) >> PAGE_SHIFT;
1214 	align = (1 << order) - 1;
1215 
1216 	spin_lock_irqsave(&mapping->lock, flags);
1217 	for (i = 0; i < mapping->nr_bitmaps; i++) {
1218 		start = bitmap_find_next_zero_area(mapping->bitmaps[i],
1219 				mapping->bits, 0, count, align);
1220 
1221 		if (start > mapping->bits)
1222 			continue;
1223 
1224 		bitmap_set(mapping->bitmaps[i], start, count);
1225 		break;
1226 	}
1227 
1228 	/*
1229 	 * No unused range found. Try to extend the existing mapping
1230 	 * and perform a second attempt to reserve an IO virtual
1231 	 * address range of size bytes.
1232 	 */
1233 	if (i == mapping->nr_bitmaps) {
1234 		if (extend_iommu_mapping(mapping)) {
1235 			spin_unlock_irqrestore(&mapping->lock, flags);
1236 			return DMA_ERROR_CODE;
1237 		}
1238 
1239 		start = bitmap_find_next_zero_area(mapping->bitmaps[i],
1240 				mapping->bits, 0, count, align);
1241 
1242 		if (start > mapping->bits) {
1243 			spin_unlock_irqrestore(&mapping->lock, flags);
1244 			return DMA_ERROR_CODE;
1245 		}
1246 
1247 		bitmap_set(mapping->bitmaps[i], start, count);
1248 	}
1249 	spin_unlock_irqrestore(&mapping->lock, flags);
1250 
1251 	iova = mapping->base + (mapping_size * i);
1252 	iova += start << PAGE_SHIFT;
1253 
1254 	return iova;
1255 }
1256 
1257 static inline void __free_iova(struct dma_iommu_mapping *mapping,
1258 			       dma_addr_t addr, size_t size)
1259 {
1260 	unsigned int start, count;
1261 	size_t mapping_size = mapping->bits << PAGE_SHIFT;
1262 	unsigned long flags;
1263 	dma_addr_t bitmap_base;
1264 	u32 bitmap_index;
1265 
1266 	if (!size)
1267 		return;
1268 
1269 	bitmap_index = (u32) (addr - mapping->base) / (u32) mapping_size;
1270 	BUG_ON(addr < mapping->base || bitmap_index > mapping->extensions);
1271 
1272 	bitmap_base = mapping->base + mapping_size * bitmap_index;
1273 
1274 	start = (addr - bitmap_base) >>	PAGE_SHIFT;
1275 
1276 	if (addr + size > bitmap_base + mapping_size) {
1277 		/*
1278 		 * The address range to be freed reaches into the iova
1279 		 * range of the next bitmap. This should not happen as
1280 		 * we don't allow this in __alloc_iova (at the
1281 		 * moment).
1282 		 */
1283 		BUG();
1284 	} else
1285 		count = size >> PAGE_SHIFT;
1286 
1287 	spin_lock_irqsave(&mapping->lock, flags);
1288 	bitmap_clear(mapping->bitmaps[bitmap_index], start, count);
1289 	spin_unlock_irqrestore(&mapping->lock, flags);
1290 }
1291 
1292 /* We'll try 2M, 1M, 64K, and finally 4K; array must end with 0! */
1293 static const int iommu_order_array[] = { 9, 8, 4, 0 };
1294 
1295 static struct page **__iommu_alloc_buffer(struct device *dev, size_t size,
1296 					  gfp_t gfp, unsigned long attrs,
1297 					  int coherent_flag)
1298 {
1299 	struct page **pages;
1300 	int count = size >> PAGE_SHIFT;
1301 	int array_size = count * sizeof(struct page *);
1302 	int i = 0;
1303 	int order_idx = 0;
1304 
1305 	if (array_size <= PAGE_SIZE)
1306 		pages = kzalloc(array_size, GFP_KERNEL);
1307 	else
1308 		pages = vzalloc(array_size);
1309 	if (!pages)
1310 		return NULL;
1311 
1312 	if (attrs & DMA_ATTR_FORCE_CONTIGUOUS)
1313 	{
1314 		unsigned long order = get_order(size);
1315 		struct page *page;
1316 
1317 		page = dma_alloc_from_contiguous(dev, count, order, gfp);
1318 		if (!page)
1319 			goto error;
1320 
1321 		__dma_clear_buffer(page, size, coherent_flag);
1322 
1323 		for (i = 0; i < count; i++)
1324 			pages[i] = page + i;
1325 
1326 		return pages;
1327 	}
1328 
1329 	/* Go straight to 4K chunks if caller says it's OK. */
1330 	if (attrs & DMA_ATTR_ALLOC_SINGLE_PAGES)
1331 		order_idx = ARRAY_SIZE(iommu_order_array) - 1;
1332 
1333 	/*
1334 	 * IOMMU can map any pages, so himem can also be used here
1335 	 */
1336 	gfp |= __GFP_NOWARN | __GFP_HIGHMEM;
1337 
1338 	while (count) {
1339 		int j, order;
1340 
1341 		order = iommu_order_array[order_idx];
1342 
1343 		/* Drop down when we get small */
1344 		if (__fls(count) < order) {
1345 			order_idx++;
1346 			continue;
1347 		}
1348 
1349 		if (order) {
1350 			/* See if it's easy to allocate a high-order chunk */
1351 			pages[i] = alloc_pages(gfp | __GFP_NORETRY, order);
1352 
1353 			/* Go down a notch at first sign of pressure */
1354 			if (!pages[i]) {
1355 				order_idx++;
1356 				continue;
1357 			}
1358 		} else {
1359 			pages[i] = alloc_pages(gfp, 0);
1360 			if (!pages[i])
1361 				goto error;
1362 		}
1363 
1364 		if (order) {
1365 			split_page(pages[i], order);
1366 			j = 1 << order;
1367 			while (--j)
1368 				pages[i + j] = pages[i] + j;
1369 		}
1370 
1371 		__dma_clear_buffer(pages[i], PAGE_SIZE << order, coherent_flag);
1372 		i += 1 << order;
1373 		count -= 1 << order;
1374 	}
1375 
1376 	return pages;
1377 error:
1378 	while (i--)
1379 		if (pages[i])
1380 			__free_pages(pages[i], 0);
1381 	kvfree(pages);
1382 	return NULL;
1383 }
1384 
1385 static int __iommu_free_buffer(struct device *dev, struct page **pages,
1386 			       size_t size, unsigned long attrs)
1387 {
1388 	int count = size >> PAGE_SHIFT;
1389 	int i;
1390 
1391 	if (attrs & DMA_ATTR_FORCE_CONTIGUOUS) {
1392 		dma_release_from_contiguous(dev, pages[0], count);
1393 	} else {
1394 		for (i = 0; i < count; i++)
1395 			if (pages[i])
1396 				__free_pages(pages[i], 0);
1397 	}
1398 
1399 	kvfree(pages);
1400 	return 0;
1401 }
1402 
1403 /*
1404  * Create a CPU mapping for a specified pages
1405  */
1406 static void *
1407 __iommu_alloc_remap(struct page **pages, size_t size, gfp_t gfp, pgprot_t prot,
1408 		    const void *caller)
1409 {
1410 	return dma_common_pages_remap(pages, size,
1411 			VM_ARM_DMA_CONSISTENT | VM_USERMAP, prot, caller);
1412 }
1413 
1414 /*
1415  * Create a mapping in device IO address space for specified pages
1416  */
1417 static dma_addr_t
1418 __iommu_create_mapping(struct device *dev, struct page **pages, size_t size,
1419 		       unsigned long attrs)
1420 {
1421 	struct dma_iommu_mapping *mapping = to_dma_iommu_mapping(dev);
1422 	unsigned int count = PAGE_ALIGN(size) >> PAGE_SHIFT;
1423 	dma_addr_t dma_addr, iova;
1424 	int i;
1425 
1426 	dma_addr = __alloc_iova(mapping, size);
1427 	if (dma_addr == DMA_ERROR_CODE)
1428 		return dma_addr;
1429 
1430 	iova = dma_addr;
1431 	for (i = 0; i < count; ) {
1432 		int ret;
1433 
1434 		unsigned int next_pfn = page_to_pfn(pages[i]) + 1;
1435 		phys_addr_t phys = page_to_phys(pages[i]);
1436 		unsigned int len, j;
1437 
1438 		for (j = i + 1; j < count; j++, next_pfn++)
1439 			if (page_to_pfn(pages[j]) != next_pfn)
1440 				break;
1441 
1442 		len = (j - i) << PAGE_SHIFT;
1443 		ret = iommu_map(mapping->domain, iova, phys, len,
1444 				__dma_info_to_prot(DMA_BIDIRECTIONAL, attrs));
1445 		if (ret < 0)
1446 			goto fail;
1447 		iova += len;
1448 		i = j;
1449 	}
1450 	return dma_addr;
1451 fail:
1452 	iommu_unmap(mapping->domain, dma_addr, iova-dma_addr);
1453 	__free_iova(mapping, dma_addr, size);
1454 	return DMA_ERROR_CODE;
1455 }
1456 
1457 static int __iommu_remove_mapping(struct device *dev, dma_addr_t iova, size_t size)
1458 {
1459 	struct dma_iommu_mapping *mapping = to_dma_iommu_mapping(dev);
1460 
1461 	/*
1462 	 * add optional in-page offset from iova to size and align
1463 	 * result to page size
1464 	 */
1465 	size = PAGE_ALIGN((iova & ~PAGE_MASK) + size);
1466 	iova &= PAGE_MASK;
1467 
1468 	iommu_unmap(mapping->domain, iova, size);
1469 	__free_iova(mapping, iova, size);
1470 	return 0;
1471 }
1472 
1473 static struct page **__atomic_get_pages(void *addr)
1474 {
1475 	struct page *page;
1476 	phys_addr_t phys;
1477 
1478 	phys = gen_pool_virt_to_phys(atomic_pool, (unsigned long)addr);
1479 	page = phys_to_page(phys);
1480 
1481 	return (struct page **)page;
1482 }
1483 
1484 static struct page **__iommu_get_pages(void *cpu_addr, unsigned long attrs)
1485 {
1486 	struct vm_struct *area;
1487 
1488 	if (__in_atomic_pool(cpu_addr, PAGE_SIZE))
1489 		return __atomic_get_pages(cpu_addr);
1490 
1491 	if (attrs & DMA_ATTR_NO_KERNEL_MAPPING)
1492 		return cpu_addr;
1493 
1494 	area = find_vm_area(cpu_addr);
1495 	if (area && (area->flags & VM_ARM_DMA_CONSISTENT))
1496 		return area->pages;
1497 	return NULL;
1498 }
1499 
1500 static void *__iommu_alloc_simple(struct device *dev, size_t size, gfp_t gfp,
1501 				  dma_addr_t *handle, int coherent_flag,
1502 				  unsigned long attrs)
1503 {
1504 	struct page *page;
1505 	void *addr;
1506 
1507 	if (coherent_flag  == COHERENT)
1508 		addr = __alloc_simple_buffer(dev, size, gfp, &page);
1509 	else
1510 		addr = __alloc_from_pool(size, &page);
1511 	if (!addr)
1512 		return NULL;
1513 
1514 	*handle = __iommu_create_mapping(dev, &page, size, attrs);
1515 	if (*handle == DMA_ERROR_CODE)
1516 		goto err_mapping;
1517 
1518 	return addr;
1519 
1520 err_mapping:
1521 	__free_from_pool(addr, size);
1522 	return NULL;
1523 }
1524 
1525 static void __iommu_free_atomic(struct device *dev, void *cpu_addr,
1526 			dma_addr_t handle, size_t size, int coherent_flag)
1527 {
1528 	__iommu_remove_mapping(dev, handle, size);
1529 	if (coherent_flag == COHERENT)
1530 		__dma_free_buffer(virt_to_page(cpu_addr), size);
1531 	else
1532 		__free_from_pool(cpu_addr, size);
1533 }
1534 
1535 static void *__arm_iommu_alloc_attrs(struct device *dev, size_t size,
1536 	    dma_addr_t *handle, gfp_t gfp, unsigned long attrs,
1537 	    int coherent_flag)
1538 {
1539 	pgprot_t prot = __get_dma_pgprot(attrs, PAGE_KERNEL);
1540 	struct page **pages;
1541 	void *addr = NULL;
1542 
1543 	*handle = DMA_ERROR_CODE;
1544 	size = PAGE_ALIGN(size);
1545 
1546 	if (coherent_flag  == COHERENT || !gfpflags_allow_blocking(gfp))
1547 		return __iommu_alloc_simple(dev, size, gfp, handle,
1548 					    coherent_flag, attrs);
1549 
1550 	/*
1551 	 * Following is a work-around (a.k.a. hack) to prevent pages
1552 	 * with __GFP_COMP being passed to split_page() which cannot
1553 	 * handle them.  The real problem is that this flag probably
1554 	 * should be 0 on ARM as it is not supported on this
1555 	 * platform; see CONFIG_HUGETLBFS.
1556 	 */
1557 	gfp &= ~(__GFP_COMP);
1558 
1559 	pages = __iommu_alloc_buffer(dev, size, gfp, attrs, coherent_flag);
1560 	if (!pages)
1561 		return NULL;
1562 
1563 	*handle = __iommu_create_mapping(dev, pages, size, attrs);
1564 	if (*handle == DMA_ERROR_CODE)
1565 		goto err_buffer;
1566 
1567 	if (attrs & DMA_ATTR_NO_KERNEL_MAPPING)
1568 		return pages;
1569 
1570 	addr = __iommu_alloc_remap(pages, size, gfp, prot,
1571 				   __builtin_return_address(0));
1572 	if (!addr)
1573 		goto err_mapping;
1574 
1575 	return addr;
1576 
1577 err_mapping:
1578 	__iommu_remove_mapping(dev, *handle, size);
1579 err_buffer:
1580 	__iommu_free_buffer(dev, pages, size, attrs);
1581 	return NULL;
1582 }
1583 
1584 static void *arm_iommu_alloc_attrs(struct device *dev, size_t size,
1585 	    dma_addr_t *handle, gfp_t gfp, unsigned long attrs)
1586 {
1587 	return __arm_iommu_alloc_attrs(dev, size, handle, gfp, attrs, NORMAL);
1588 }
1589 
1590 static void *arm_coherent_iommu_alloc_attrs(struct device *dev, size_t size,
1591 		    dma_addr_t *handle, gfp_t gfp, unsigned long attrs)
1592 {
1593 	return __arm_iommu_alloc_attrs(dev, size, handle, gfp, attrs, COHERENT);
1594 }
1595 
1596 static int __arm_iommu_mmap_attrs(struct device *dev, struct vm_area_struct *vma,
1597 		    void *cpu_addr, dma_addr_t dma_addr, size_t size,
1598 		    unsigned long attrs)
1599 {
1600 	unsigned long uaddr = vma->vm_start;
1601 	unsigned long usize = vma->vm_end - vma->vm_start;
1602 	struct page **pages = __iommu_get_pages(cpu_addr, attrs);
1603 	unsigned long nr_pages = PAGE_ALIGN(size) >> PAGE_SHIFT;
1604 	unsigned long off = vma->vm_pgoff;
1605 
1606 	if (!pages)
1607 		return -ENXIO;
1608 
1609 	if (off >= nr_pages || (usize >> PAGE_SHIFT) > nr_pages - off)
1610 		return -ENXIO;
1611 
1612 	pages += off;
1613 
1614 	do {
1615 		int ret = vm_insert_page(vma, uaddr, *pages++);
1616 		if (ret) {
1617 			pr_err("Remapping memory failed: %d\n", ret);
1618 			return ret;
1619 		}
1620 		uaddr += PAGE_SIZE;
1621 		usize -= PAGE_SIZE;
1622 	} while (usize > 0);
1623 
1624 	return 0;
1625 }
1626 static int arm_iommu_mmap_attrs(struct device *dev,
1627 		struct vm_area_struct *vma, void *cpu_addr,
1628 		dma_addr_t dma_addr, size_t size, unsigned long attrs)
1629 {
1630 	vma->vm_page_prot = __get_dma_pgprot(attrs, vma->vm_page_prot);
1631 
1632 	return __arm_iommu_mmap_attrs(dev, vma, cpu_addr, dma_addr, size, attrs);
1633 }
1634 
1635 static int arm_coherent_iommu_mmap_attrs(struct device *dev,
1636 		struct vm_area_struct *vma, void *cpu_addr,
1637 		dma_addr_t dma_addr, size_t size, unsigned long attrs)
1638 {
1639 	return __arm_iommu_mmap_attrs(dev, vma, cpu_addr, dma_addr, size, attrs);
1640 }
1641 
1642 /*
1643  * free a page as defined by the above mapping.
1644  * Must not be called with IRQs disabled.
1645  */
1646 void __arm_iommu_free_attrs(struct device *dev, size_t size, void *cpu_addr,
1647 	dma_addr_t handle, unsigned long attrs, int coherent_flag)
1648 {
1649 	struct page **pages;
1650 	size = PAGE_ALIGN(size);
1651 
1652 	if (coherent_flag == COHERENT || __in_atomic_pool(cpu_addr, size)) {
1653 		__iommu_free_atomic(dev, cpu_addr, handle, size, coherent_flag);
1654 		return;
1655 	}
1656 
1657 	pages = __iommu_get_pages(cpu_addr, attrs);
1658 	if (!pages) {
1659 		WARN(1, "trying to free invalid coherent area: %p\n", cpu_addr);
1660 		return;
1661 	}
1662 
1663 	if ((attrs & DMA_ATTR_NO_KERNEL_MAPPING) == 0) {
1664 		dma_common_free_remap(cpu_addr, size,
1665 			VM_ARM_DMA_CONSISTENT | VM_USERMAP);
1666 	}
1667 
1668 	__iommu_remove_mapping(dev, handle, size);
1669 	__iommu_free_buffer(dev, pages, size, attrs);
1670 }
1671 
1672 void arm_iommu_free_attrs(struct device *dev, size_t size,
1673 		    void *cpu_addr, dma_addr_t handle, unsigned long attrs)
1674 {
1675 	__arm_iommu_free_attrs(dev, size, cpu_addr, handle, attrs, NORMAL);
1676 }
1677 
1678 void arm_coherent_iommu_free_attrs(struct device *dev, size_t size,
1679 		    void *cpu_addr, dma_addr_t handle, unsigned long attrs)
1680 {
1681 	__arm_iommu_free_attrs(dev, size, cpu_addr, handle, attrs, COHERENT);
1682 }
1683 
1684 static int arm_iommu_get_sgtable(struct device *dev, struct sg_table *sgt,
1685 				 void *cpu_addr, dma_addr_t dma_addr,
1686 				 size_t size, unsigned long attrs)
1687 {
1688 	unsigned int count = PAGE_ALIGN(size) >> PAGE_SHIFT;
1689 	struct page **pages = __iommu_get_pages(cpu_addr, attrs);
1690 
1691 	if (!pages)
1692 		return -ENXIO;
1693 
1694 	return sg_alloc_table_from_pages(sgt, pages, count, 0, size,
1695 					 GFP_KERNEL);
1696 }
1697 
1698 /*
1699  * Map a part of the scatter-gather list into contiguous io address space
1700  */
1701 static int __map_sg_chunk(struct device *dev, struct scatterlist *sg,
1702 			  size_t size, dma_addr_t *handle,
1703 			  enum dma_data_direction dir, unsigned long attrs,
1704 			  bool is_coherent)
1705 {
1706 	struct dma_iommu_mapping *mapping = to_dma_iommu_mapping(dev);
1707 	dma_addr_t iova, iova_base;
1708 	int ret = 0;
1709 	unsigned int count;
1710 	struct scatterlist *s;
1711 	int prot;
1712 
1713 	size = PAGE_ALIGN(size);
1714 	*handle = DMA_ERROR_CODE;
1715 
1716 	iova_base = iova = __alloc_iova(mapping, size);
1717 	if (iova == DMA_ERROR_CODE)
1718 		return -ENOMEM;
1719 
1720 	for (count = 0, s = sg; count < (size >> PAGE_SHIFT); s = sg_next(s)) {
1721 		phys_addr_t phys = page_to_phys(sg_page(s));
1722 		unsigned int len = PAGE_ALIGN(s->offset + s->length);
1723 
1724 		if (!is_coherent && (attrs & DMA_ATTR_SKIP_CPU_SYNC) == 0)
1725 			__dma_page_cpu_to_dev(sg_page(s), s->offset, s->length, dir);
1726 
1727 		prot = __dma_info_to_prot(dir, attrs);
1728 
1729 		ret = iommu_map(mapping->domain, iova, phys, len, prot);
1730 		if (ret < 0)
1731 			goto fail;
1732 		count += len >> PAGE_SHIFT;
1733 		iova += len;
1734 	}
1735 	*handle = iova_base;
1736 
1737 	return 0;
1738 fail:
1739 	iommu_unmap(mapping->domain, iova_base, count * PAGE_SIZE);
1740 	__free_iova(mapping, iova_base, size);
1741 	return ret;
1742 }
1743 
1744 static int __iommu_map_sg(struct device *dev, struct scatterlist *sg, int nents,
1745 		     enum dma_data_direction dir, unsigned long attrs,
1746 		     bool is_coherent)
1747 {
1748 	struct scatterlist *s = sg, *dma = sg, *start = sg;
1749 	int i, count = 0;
1750 	unsigned int offset = s->offset;
1751 	unsigned int size = s->offset + s->length;
1752 	unsigned int max = dma_get_max_seg_size(dev);
1753 
1754 	for (i = 1; i < nents; i++) {
1755 		s = sg_next(s);
1756 
1757 		s->dma_address = DMA_ERROR_CODE;
1758 		s->dma_length = 0;
1759 
1760 		if (s->offset || (size & ~PAGE_MASK) || size + s->length > max) {
1761 			if (__map_sg_chunk(dev, start, size, &dma->dma_address,
1762 			    dir, attrs, is_coherent) < 0)
1763 				goto bad_mapping;
1764 
1765 			dma->dma_address += offset;
1766 			dma->dma_length = size - offset;
1767 
1768 			size = offset = s->offset;
1769 			start = s;
1770 			dma = sg_next(dma);
1771 			count += 1;
1772 		}
1773 		size += s->length;
1774 	}
1775 	if (__map_sg_chunk(dev, start, size, &dma->dma_address, dir, attrs,
1776 		is_coherent) < 0)
1777 		goto bad_mapping;
1778 
1779 	dma->dma_address += offset;
1780 	dma->dma_length = size - offset;
1781 
1782 	return count+1;
1783 
1784 bad_mapping:
1785 	for_each_sg(sg, s, count, i)
1786 		__iommu_remove_mapping(dev, sg_dma_address(s), sg_dma_len(s));
1787 	return 0;
1788 }
1789 
1790 /**
1791  * arm_coherent_iommu_map_sg - map a set of SG buffers for streaming mode DMA
1792  * @dev: valid struct device pointer
1793  * @sg: list of buffers
1794  * @nents: number of buffers to map
1795  * @dir: DMA transfer direction
1796  *
1797  * Map a set of i/o coherent buffers described by scatterlist in streaming
1798  * mode for DMA. The scatter gather list elements are merged together (if
1799  * possible) and tagged with the appropriate dma address and length. They are
1800  * obtained via sg_dma_{address,length}.
1801  */
1802 int arm_coherent_iommu_map_sg(struct device *dev, struct scatterlist *sg,
1803 		int nents, enum dma_data_direction dir, unsigned long attrs)
1804 {
1805 	return __iommu_map_sg(dev, sg, nents, dir, attrs, true);
1806 }
1807 
1808 /**
1809  * arm_iommu_map_sg - map a set of SG buffers for streaming mode DMA
1810  * @dev: valid struct device pointer
1811  * @sg: list of buffers
1812  * @nents: number of buffers to map
1813  * @dir: DMA transfer direction
1814  *
1815  * Map a set of buffers described by scatterlist in streaming mode for DMA.
1816  * The scatter gather list elements are merged together (if possible) and
1817  * tagged with the appropriate dma address and length. They are obtained via
1818  * sg_dma_{address,length}.
1819  */
1820 int arm_iommu_map_sg(struct device *dev, struct scatterlist *sg,
1821 		int nents, enum dma_data_direction dir, unsigned long attrs)
1822 {
1823 	return __iommu_map_sg(dev, sg, nents, dir, attrs, false);
1824 }
1825 
1826 static void __iommu_unmap_sg(struct device *dev, struct scatterlist *sg,
1827 		int nents, enum dma_data_direction dir,
1828 		unsigned long attrs, bool is_coherent)
1829 {
1830 	struct scatterlist *s;
1831 	int i;
1832 
1833 	for_each_sg(sg, s, nents, i) {
1834 		if (sg_dma_len(s))
1835 			__iommu_remove_mapping(dev, sg_dma_address(s),
1836 					       sg_dma_len(s));
1837 		if (!is_coherent && (attrs & DMA_ATTR_SKIP_CPU_SYNC) == 0)
1838 			__dma_page_dev_to_cpu(sg_page(s), s->offset,
1839 					      s->length, dir);
1840 	}
1841 }
1842 
1843 /**
1844  * arm_coherent_iommu_unmap_sg - unmap a set of SG buffers mapped by dma_map_sg
1845  * @dev: valid struct device pointer
1846  * @sg: list of buffers
1847  * @nents: number of buffers to unmap (same as was passed to dma_map_sg)
1848  * @dir: DMA transfer direction (same as was passed to dma_map_sg)
1849  *
1850  * Unmap a set of streaming mode DMA translations.  Again, CPU access
1851  * rules concerning calls here are the same as for dma_unmap_single().
1852  */
1853 void arm_coherent_iommu_unmap_sg(struct device *dev, struct scatterlist *sg,
1854 		int nents, enum dma_data_direction dir,
1855 		unsigned long attrs)
1856 {
1857 	__iommu_unmap_sg(dev, sg, nents, dir, attrs, true);
1858 }
1859 
1860 /**
1861  * arm_iommu_unmap_sg - unmap a set of SG buffers mapped by dma_map_sg
1862  * @dev: valid struct device pointer
1863  * @sg: list of buffers
1864  * @nents: number of buffers to unmap (same as was passed to dma_map_sg)
1865  * @dir: DMA transfer direction (same as was passed to dma_map_sg)
1866  *
1867  * Unmap a set of streaming mode DMA translations.  Again, CPU access
1868  * rules concerning calls here are the same as for dma_unmap_single().
1869  */
1870 void arm_iommu_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
1871 			enum dma_data_direction dir,
1872 			unsigned long attrs)
1873 {
1874 	__iommu_unmap_sg(dev, sg, nents, dir, attrs, false);
1875 }
1876 
1877 /**
1878  * arm_iommu_sync_sg_for_cpu
1879  * @dev: valid struct device pointer
1880  * @sg: list of buffers
1881  * @nents: number of buffers to map (returned from dma_map_sg)
1882  * @dir: DMA transfer direction (same as was passed to dma_map_sg)
1883  */
1884 void arm_iommu_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
1885 			int nents, enum dma_data_direction dir)
1886 {
1887 	struct scatterlist *s;
1888 	int i;
1889 
1890 	for_each_sg(sg, s, nents, i)
1891 		__dma_page_dev_to_cpu(sg_page(s), s->offset, s->length, dir);
1892 
1893 }
1894 
1895 /**
1896  * arm_iommu_sync_sg_for_device
1897  * @dev: valid struct device pointer
1898  * @sg: list of buffers
1899  * @nents: number of buffers to map (returned from dma_map_sg)
1900  * @dir: DMA transfer direction (same as was passed to dma_map_sg)
1901  */
1902 void arm_iommu_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
1903 			int nents, enum dma_data_direction dir)
1904 {
1905 	struct scatterlist *s;
1906 	int i;
1907 
1908 	for_each_sg(sg, s, nents, i)
1909 		__dma_page_cpu_to_dev(sg_page(s), s->offset, s->length, dir);
1910 }
1911 
1912 
1913 /**
1914  * arm_coherent_iommu_map_page
1915  * @dev: valid struct device pointer
1916  * @page: page that buffer resides in
1917  * @offset: offset into page for start of buffer
1918  * @size: size of buffer to map
1919  * @dir: DMA transfer direction
1920  *
1921  * Coherent IOMMU aware version of arm_dma_map_page()
1922  */
1923 static dma_addr_t arm_coherent_iommu_map_page(struct device *dev, struct page *page,
1924 	     unsigned long offset, size_t size, enum dma_data_direction dir,
1925 	     unsigned long attrs)
1926 {
1927 	struct dma_iommu_mapping *mapping = to_dma_iommu_mapping(dev);
1928 	dma_addr_t dma_addr;
1929 	int ret, prot, len = PAGE_ALIGN(size + offset);
1930 
1931 	dma_addr = __alloc_iova(mapping, len);
1932 	if (dma_addr == DMA_ERROR_CODE)
1933 		return dma_addr;
1934 
1935 	prot = __dma_info_to_prot(dir, attrs);
1936 
1937 	ret = iommu_map(mapping->domain, dma_addr, page_to_phys(page), len, prot);
1938 	if (ret < 0)
1939 		goto fail;
1940 
1941 	return dma_addr + offset;
1942 fail:
1943 	__free_iova(mapping, dma_addr, len);
1944 	return DMA_ERROR_CODE;
1945 }
1946 
1947 /**
1948  * arm_iommu_map_page
1949  * @dev: valid struct device pointer
1950  * @page: page that buffer resides in
1951  * @offset: offset into page for start of buffer
1952  * @size: size of buffer to map
1953  * @dir: DMA transfer direction
1954  *
1955  * IOMMU aware version of arm_dma_map_page()
1956  */
1957 static dma_addr_t arm_iommu_map_page(struct device *dev, struct page *page,
1958 	     unsigned long offset, size_t size, enum dma_data_direction dir,
1959 	     unsigned long attrs)
1960 {
1961 	if ((attrs & DMA_ATTR_SKIP_CPU_SYNC) == 0)
1962 		__dma_page_cpu_to_dev(page, offset, size, dir);
1963 
1964 	return arm_coherent_iommu_map_page(dev, page, offset, size, dir, attrs);
1965 }
1966 
1967 /**
1968  * arm_coherent_iommu_unmap_page
1969  * @dev: valid struct device pointer
1970  * @handle: DMA address of buffer
1971  * @size: size of buffer (same as passed to dma_map_page)
1972  * @dir: DMA transfer direction (same as passed to dma_map_page)
1973  *
1974  * Coherent IOMMU aware version of arm_dma_unmap_page()
1975  */
1976 static void arm_coherent_iommu_unmap_page(struct device *dev, dma_addr_t handle,
1977 		size_t size, enum dma_data_direction dir, unsigned long attrs)
1978 {
1979 	struct dma_iommu_mapping *mapping = to_dma_iommu_mapping(dev);
1980 	dma_addr_t iova = handle & PAGE_MASK;
1981 	int offset = handle & ~PAGE_MASK;
1982 	int len = PAGE_ALIGN(size + offset);
1983 
1984 	if (!iova)
1985 		return;
1986 
1987 	iommu_unmap(mapping->domain, iova, len);
1988 	__free_iova(mapping, iova, len);
1989 }
1990 
1991 /**
1992  * arm_iommu_unmap_page
1993  * @dev: valid struct device pointer
1994  * @handle: DMA address of buffer
1995  * @size: size of buffer (same as passed to dma_map_page)
1996  * @dir: DMA transfer direction (same as passed to dma_map_page)
1997  *
1998  * IOMMU aware version of arm_dma_unmap_page()
1999  */
2000 static void arm_iommu_unmap_page(struct device *dev, dma_addr_t handle,
2001 		size_t size, enum dma_data_direction dir, unsigned long attrs)
2002 {
2003 	struct dma_iommu_mapping *mapping = to_dma_iommu_mapping(dev);
2004 	dma_addr_t iova = handle & PAGE_MASK;
2005 	struct page *page = phys_to_page(iommu_iova_to_phys(mapping->domain, iova));
2006 	int offset = handle & ~PAGE_MASK;
2007 	int len = PAGE_ALIGN(size + offset);
2008 
2009 	if (!iova)
2010 		return;
2011 
2012 	if ((attrs & DMA_ATTR_SKIP_CPU_SYNC) == 0)
2013 		__dma_page_dev_to_cpu(page, offset, size, dir);
2014 
2015 	iommu_unmap(mapping->domain, iova, len);
2016 	__free_iova(mapping, iova, len);
2017 }
2018 
2019 /**
2020  * arm_iommu_map_resource - map a device resource for DMA
2021  * @dev: valid struct device pointer
2022  * @phys_addr: physical address of resource
2023  * @size: size of resource to map
2024  * @dir: DMA transfer direction
2025  */
2026 static dma_addr_t arm_iommu_map_resource(struct device *dev,
2027 		phys_addr_t phys_addr, size_t size,
2028 		enum dma_data_direction dir, unsigned long attrs)
2029 {
2030 	struct dma_iommu_mapping *mapping = to_dma_iommu_mapping(dev);
2031 	dma_addr_t dma_addr;
2032 	int ret, prot;
2033 	phys_addr_t addr = phys_addr & PAGE_MASK;
2034 	unsigned int offset = phys_addr & ~PAGE_MASK;
2035 	size_t len = PAGE_ALIGN(size + offset);
2036 
2037 	dma_addr = __alloc_iova(mapping, len);
2038 	if (dma_addr == DMA_ERROR_CODE)
2039 		return dma_addr;
2040 
2041 	prot = __dma_info_to_prot(dir, attrs) | IOMMU_MMIO;
2042 
2043 	ret = iommu_map(mapping->domain, dma_addr, addr, len, prot);
2044 	if (ret < 0)
2045 		goto fail;
2046 
2047 	return dma_addr + offset;
2048 fail:
2049 	__free_iova(mapping, dma_addr, len);
2050 	return DMA_ERROR_CODE;
2051 }
2052 
2053 /**
2054  * arm_iommu_unmap_resource - unmap a device DMA resource
2055  * @dev: valid struct device pointer
2056  * @dma_handle: DMA address to resource
2057  * @size: size of resource to map
2058  * @dir: DMA transfer direction
2059  */
2060 static void arm_iommu_unmap_resource(struct device *dev, dma_addr_t dma_handle,
2061 		size_t size, enum dma_data_direction dir,
2062 		unsigned long attrs)
2063 {
2064 	struct dma_iommu_mapping *mapping = to_dma_iommu_mapping(dev);
2065 	dma_addr_t iova = dma_handle & PAGE_MASK;
2066 	unsigned int offset = dma_handle & ~PAGE_MASK;
2067 	size_t len = PAGE_ALIGN(size + offset);
2068 
2069 	if (!iova)
2070 		return;
2071 
2072 	iommu_unmap(mapping->domain, iova, len);
2073 	__free_iova(mapping, iova, len);
2074 }
2075 
2076 static void arm_iommu_sync_single_for_cpu(struct device *dev,
2077 		dma_addr_t handle, size_t size, enum dma_data_direction dir)
2078 {
2079 	struct dma_iommu_mapping *mapping = to_dma_iommu_mapping(dev);
2080 	dma_addr_t iova = handle & PAGE_MASK;
2081 	struct page *page = phys_to_page(iommu_iova_to_phys(mapping->domain, iova));
2082 	unsigned int offset = handle & ~PAGE_MASK;
2083 
2084 	if (!iova)
2085 		return;
2086 
2087 	__dma_page_dev_to_cpu(page, offset, size, dir);
2088 }
2089 
2090 static void arm_iommu_sync_single_for_device(struct device *dev,
2091 		dma_addr_t handle, size_t size, enum dma_data_direction dir)
2092 {
2093 	struct dma_iommu_mapping *mapping = to_dma_iommu_mapping(dev);
2094 	dma_addr_t iova = handle & PAGE_MASK;
2095 	struct page *page = phys_to_page(iommu_iova_to_phys(mapping->domain, iova));
2096 	unsigned int offset = handle & ~PAGE_MASK;
2097 
2098 	if (!iova)
2099 		return;
2100 
2101 	__dma_page_cpu_to_dev(page, offset, size, dir);
2102 }
2103 
2104 struct dma_map_ops iommu_ops = {
2105 	.alloc		= arm_iommu_alloc_attrs,
2106 	.free		= arm_iommu_free_attrs,
2107 	.mmap		= arm_iommu_mmap_attrs,
2108 	.get_sgtable	= arm_iommu_get_sgtable,
2109 
2110 	.map_page		= arm_iommu_map_page,
2111 	.unmap_page		= arm_iommu_unmap_page,
2112 	.sync_single_for_cpu	= arm_iommu_sync_single_for_cpu,
2113 	.sync_single_for_device	= arm_iommu_sync_single_for_device,
2114 
2115 	.map_sg			= arm_iommu_map_sg,
2116 	.unmap_sg		= arm_iommu_unmap_sg,
2117 	.sync_sg_for_cpu	= arm_iommu_sync_sg_for_cpu,
2118 	.sync_sg_for_device	= arm_iommu_sync_sg_for_device,
2119 
2120 	.map_resource		= arm_iommu_map_resource,
2121 	.unmap_resource		= arm_iommu_unmap_resource,
2122 };
2123 
2124 struct dma_map_ops iommu_coherent_ops = {
2125 	.alloc		= arm_coherent_iommu_alloc_attrs,
2126 	.free		= arm_coherent_iommu_free_attrs,
2127 	.mmap		= arm_coherent_iommu_mmap_attrs,
2128 	.get_sgtable	= arm_iommu_get_sgtable,
2129 
2130 	.map_page	= arm_coherent_iommu_map_page,
2131 	.unmap_page	= arm_coherent_iommu_unmap_page,
2132 
2133 	.map_sg		= arm_coherent_iommu_map_sg,
2134 	.unmap_sg	= arm_coherent_iommu_unmap_sg,
2135 
2136 	.map_resource	= arm_iommu_map_resource,
2137 	.unmap_resource	= arm_iommu_unmap_resource,
2138 };
2139 
2140 /**
2141  * arm_iommu_create_mapping
2142  * @bus: pointer to the bus holding the client device (for IOMMU calls)
2143  * @base: start address of the valid IO address space
2144  * @size: maximum size of the valid IO address space
2145  *
2146  * Creates a mapping structure which holds information about used/unused
2147  * IO address ranges, which is required to perform memory allocation and
2148  * mapping with IOMMU aware functions.
2149  *
2150  * The client device need to be attached to the mapping with
2151  * arm_iommu_attach_device function.
2152  */
2153 struct dma_iommu_mapping *
2154 arm_iommu_create_mapping(struct bus_type *bus, dma_addr_t base, u64 size)
2155 {
2156 	unsigned int bits = size >> PAGE_SHIFT;
2157 	unsigned int bitmap_size = BITS_TO_LONGS(bits) * sizeof(long);
2158 	struct dma_iommu_mapping *mapping;
2159 	int extensions = 1;
2160 	int err = -ENOMEM;
2161 
2162 	/* currently only 32-bit DMA address space is supported */
2163 	if (size > DMA_BIT_MASK(32) + 1)
2164 		return ERR_PTR(-ERANGE);
2165 
2166 	if (!bitmap_size)
2167 		return ERR_PTR(-EINVAL);
2168 
2169 	if (bitmap_size > PAGE_SIZE) {
2170 		extensions = bitmap_size / PAGE_SIZE;
2171 		bitmap_size = PAGE_SIZE;
2172 	}
2173 
2174 	mapping = kzalloc(sizeof(struct dma_iommu_mapping), GFP_KERNEL);
2175 	if (!mapping)
2176 		goto err;
2177 
2178 	mapping->bitmap_size = bitmap_size;
2179 	mapping->bitmaps = kzalloc(extensions * sizeof(unsigned long *),
2180 				GFP_KERNEL);
2181 	if (!mapping->bitmaps)
2182 		goto err2;
2183 
2184 	mapping->bitmaps[0] = kzalloc(bitmap_size, GFP_KERNEL);
2185 	if (!mapping->bitmaps[0])
2186 		goto err3;
2187 
2188 	mapping->nr_bitmaps = 1;
2189 	mapping->extensions = extensions;
2190 	mapping->base = base;
2191 	mapping->bits = BITS_PER_BYTE * bitmap_size;
2192 
2193 	spin_lock_init(&mapping->lock);
2194 
2195 	mapping->domain = iommu_domain_alloc(bus);
2196 	if (!mapping->domain)
2197 		goto err4;
2198 
2199 	kref_init(&mapping->kref);
2200 	return mapping;
2201 err4:
2202 	kfree(mapping->bitmaps[0]);
2203 err3:
2204 	kfree(mapping->bitmaps);
2205 err2:
2206 	kfree(mapping);
2207 err:
2208 	return ERR_PTR(err);
2209 }
2210 EXPORT_SYMBOL_GPL(arm_iommu_create_mapping);
2211 
2212 static void release_iommu_mapping(struct kref *kref)
2213 {
2214 	int i;
2215 	struct dma_iommu_mapping *mapping =
2216 		container_of(kref, struct dma_iommu_mapping, kref);
2217 
2218 	iommu_domain_free(mapping->domain);
2219 	for (i = 0; i < mapping->nr_bitmaps; i++)
2220 		kfree(mapping->bitmaps[i]);
2221 	kfree(mapping->bitmaps);
2222 	kfree(mapping);
2223 }
2224 
2225 static int extend_iommu_mapping(struct dma_iommu_mapping *mapping)
2226 {
2227 	int next_bitmap;
2228 
2229 	if (mapping->nr_bitmaps >= mapping->extensions)
2230 		return -EINVAL;
2231 
2232 	next_bitmap = mapping->nr_bitmaps;
2233 	mapping->bitmaps[next_bitmap] = kzalloc(mapping->bitmap_size,
2234 						GFP_ATOMIC);
2235 	if (!mapping->bitmaps[next_bitmap])
2236 		return -ENOMEM;
2237 
2238 	mapping->nr_bitmaps++;
2239 
2240 	return 0;
2241 }
2242 
2243 void arm_iommu_release_mapping(struct dma_iommu_mapping *mapping)
2244 {
2245 	if (mapping)
2246 		kref_put(&mapping->kref, release_iommu_mapping);
2247 }
2248 EXPORT_SYMBOL_GPL(arm_iommu_release_mapping);
2249 
2250 static int __arm_iommu_attach_device(struct device *dev,
2251 				     struct dma_iommu_mapping *mapping)
2252 {
2253 	int err;
2254 
2255 	err = iommu_attach_device(mapping->domain, dev);
2256 	if (err)
2257 		return err;
2258 
2259 	kref_get(&mapping->kref);
2260 	to_dma_iommu_mapping(dev) = mapping;
2261 
2262 	pr_debug("Attached IOMMU controller to %s device.\n", dev_name(dev));
2263 	return 0;
2264 }
2265 
2266 /**
2267  * arm_iommu_attach_device
2268  * @dev: valid struct device pointer
2269  * @mapping: io address space mapping structure (returned from
2270  *	arm_iommu_create_mapping)
2271  *
2272  * Attaches specified io address space mapping to the provided device.
2273  * This replaces the dma operations (dma_map_ops pointer) with the
2274  * IOMMU aware version.
2275  *
2276  * More than one client might be attached to the same io address space
2277  * mapping.
2278  */
2279 int arm_iommu_attach_device(struct device *dev,
2280 			    struct dma_iommu_mapping *mapping)
2281 {
2282 	int err;
2283 
2284 	err = __arm_iommu_attach_device(dev, mapping);
2285 	if (err)
2286 		return err;
2287 
2288 	set_dma_ops(dev, &iommu_ops);
2289 	return 0;
2290 }
2291 EXPORT_SYMBOL_GPL(arm_iommu_attach_device);
2292 
2293 static void __arm_iommu_detach_device(struct device *dev)
2294 {
2295 	struct dma_iommu_mapping *mapping;
2296 
2297 	mapping = to_dma_iommu_mapping(dev);
2298 	if (!mapping) {
2299 		dev_warn(dev, "Not attached\n");
2300 		return;
2301 	}
2302 
2303 	iommu_detach_device(mapping->domain, dev);
2304 	kref_put(&mapping->kref, release_iommu_mapping);
2305 	to_dma_iommu_mapping(dev) = NULL;
2306 
2307 	pr_debug("Detached IOMMU controller from %s device.\n", dev_name(dev));
2308 }
2309 
2310 /**
2311  * arm_iommu_detach_device
2312  * @dev: valid struct device pointer
2313  *
2314  * Detaches the provided device from a previously attached map.
2315  * This voids the dma operations (dma_map_ops pointer)
2316  */
2317 void arm_iommu_detach_device(struct device *dev)
2318 {
2319 	__arm_iommu_detach_device(dev);
2320 	set_dma_ops(dev, NULL);
2321 }
2322 EXPORT_SYMBOL_GPL(arm_iommu_detach_device);
2323 
2324 static struct dma_map_ops *arm_get_iommu_dma_map_ops(bool coherent)
2325 {
2326 	return coherent ? &iommu_coherent_ops : &iommu_ops;
2327 }
2328 
2329 static bool arm_setup_iommu_dma_ops(struct device *dev, u64 dma_base, u64 size,
2330 				    const struct iommu_ops *iommu)
2331 {
2332 	struct dma_iommu_mapping *mapping;
2333 
2334 	if (!iommu)
2335 		return false;
2336 
2337 	mapping = arm_iommu_create_mapping(dev->bus, dma_base, size);
2338 	if (IS_ERR(mapping)) {
2339 		pr_warn("Failed to create %llu-byte IOMMU mapping for device %s\n",
2340 				size, dev_name(dev));
2341 		return false;
2342 	}
2343 
2344 	if (__arm_iommu_attach_device(dev, mapping)) {
2345 		pr_warn("Failed to attached device %s to IOMMU_mapping\n",
2346 				dev_name(dev));
2347 		arm_iommu_release_mapping(mapping);
2348 		return false;
2349 	}
2350 
2351 	return true;
2352 }
2353 
2354 static void arm_teardown_iommu_dma_ops(struct device *dev)
2355 {
2356 	struct dma_iommu_mapping *mapping = to_dma_iommu_mapping(dev);
2357 
2358 	if (!mapping)
2359 		return;
2360 
2361 	__arm_iommu_detach_device(dev);
2362 	arm_iommu_release_mapping(mapping);
2363 }
2364 
2365 #else
2366 
2367 static bool arm_setup_iommu_dma_ops(struct device *dev, u64 dma_base, u64 size,
2368 				    const struct iommu_ops *iommu)
2369 {
2370 	return false;
2371 }
2372 
2373 static void arm_teardown_iommu_dma_ops(struct device *dev) { }
2374 
2375 #define arm_get_iommu_dma_map_ops arm_get_dma_map_ops
2376 
2377 #endif	/* CONFIG_ARM_DMA_USE_IOMMU */
2378 
2379 static struct dma_map_ops *arm_get_dma_map_ops(bool coherent)
2380 {
2381 	return coherent ? &arm_coherent_dma_ops : &arm_dma_ops;
2382 }
2383 
2384 void arch_setup_dma_ops(struct device *dev, u64 dma_base, u64 size,
2385 			const struct iommu_ops *iommu, bool coherent)
2386 {
2387 	struct dma_map_ops *dma_ops;
2388 
2389 	dev->archdata.dma_coherent = coherent;
2390 	if (arm_setup_iommu_dma_ops(dev, dma_base, size, iommu))
2391 		dma_ops = arm_get_iommu_dma_map_ops(coherent);
2392 	else
2393 		dma_ops = arm_get_dma_map_ops(coherent);
2394 
2395 	set_dma_ops(dev, dma_ops);
2396 }
2397 
2398 void arch_teardown_dma_ops(struct device *dev)
2399 {
2400 	arm_teardown_iommu_dma_ops(dev);
2401 }
2402