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