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