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