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