Back to home page

LXR

 
 

    


0001 /*
0002  * Dynamic DMA mapping support.
0003  *
0004  * This implementation is a fallback for platforms that do not support
0005  * I/O TLBs (aka DMA address translation hardware).
0006  * Copyright (C) 2000 Asit Mallick <Asit.K.Mallick@intel.com>
0007  * Copyright (C) 2000 Goutham Rao <goutham.rao@intel.com>
0008  * Copyright (C) 2000, 2003 Hewlett-Packard Co
0009  *  David Mosberger-Tang <davidm@hpl.hp.com>
0010  *
0011  * 03/05/07 davidm  Switch from PCI-DMA to generic device DMA API.
0012  * 00/12/13 davidm  Rename to swiotlb.c and add mark_clean() to avoid
0013  *          unnecessary i-cache flushing.
0014  * 04/07/.. ak      Better overflow handling. Assorted fixes.
0015  * 05/09/10 linville    Add support for syncing ranges, support syncing for
0016  *          DMA_BIDIRECTIONAL mappings, miscellaneous cleanup.
0017  * 08/12/11 beckyb  Add highmem support
0018  */
0019 
0020 #include <linux/cache.h>
0021 #include <linux/dma-mapping.h>
0022 #include <linux/mm.h>
0023 #include <linux/export.h>
0024 #include <linux/spinlock.h>
0025 #include <linux/string.h>
0026 #include <linux/swiotlb.h>
0027 #include <linux/pfn.h>
0028 #include <linux/types.h>
0029 #include <linux/ctype.h>
0030 #include <linux/highmem.h>
0031 #include <linux/gfp.h>
0032 #include <linux/scatterlist.h>
0033 
0034 #include <asm/io.h>
0035 #include <asm/dma.h>
0036 
0037 #include <linux/init.h>
0038 #include <linux/bootmem.h>
0039 #include <linux/iommu-helper.h>
0040 
0041 #define CREATE_TRACE_POINTS
0042 #include <trace/events/swiotlb.h>
0043 
0044 #define OFFSET(val,align) ((unsigned long)  \
0045                        ( (val) & ( (align) - 1)))
0046 
0047 #define SLABS_PER_PAGE (1 << (PAGE_SHIFT - IO_TLB_SHIFT))
0048 
0049 /*
0050  * Minimum IO TLB size to bother booting with.  Systems with mainly
0051  * 64bit capable cards will only lightly use the swiotlb.  If we can't
0052  * allocate a contiguous 1MB, we're probably in trouble anyway.
0053  */
0054 #define IO_TLB_MIN_SLABS ((1<<20) >> IO_TLB_SHIFT)
0055 
0056 enum swiotlb_force swiotlb_force;
0057 
0058 /*
0059  * Used to do a quick range check in swiotlb_tbl_unmap_single and
0060  * swiotlb_tbl_sync_single_*, to see if the memory was in fact allocated by this
0061  * API.
0062  */
0063 static phys_addr_t io_tlb_start, io_tlb_end;
0064 
0065 /*
0066  * The number of IO TLB blocks (in groups of 64) between io_tlb_start and
0067  * io_tlb_end.  This is command line adjustable via setup_io_tlb_npages.
0068  */
0069 static unsigned long io_tlb_nslabs;
0070 
0071 /*
0072  * When the IOMMU overflows we return a fallback buffer. This sets the size.
0073  */
0074 static unsigned long io_tlb_overflow = 32*1024;
0075 
0076 static phys_addr_t io_tlb_overflow_buffer;
0077 
0078 /*
0079  * This is a free list describing the number of free entries available from
0080  * each index
0081  */
0082 static unsigned int *io_tlb_list;
0083 static unsigned int io_tlb_index;
0084 
0085 /*
0086  * Max segment that we can provide which (if pages are contingous) will
0087  * not be bounced (unless SWIOTLB_FORCE is set).
0088  */
0089 unsigned int max_segment;
0090 
0091 /*
0092  * We need to save away the original address corresponding to a mapped entry
0093  * for the sync operations.
0094  */
0095 #define INVALID_PHYS_ADDR (~(phys_addr_t)0)
0096 static phys_addr_t *io_tlb_orig_addr;
0097 
0098 /*
0099  * Protect the above data structures in the map and unmap calls
0100  */
0101 static DEFINE_SPINLOCK(io_tlb_lock);
0102 
0103 static int late_alloc;
0104 
0105 static int __init
0106 setup_io_tlb_npages(char *str)
0107 {
0108     if (isdigit(*str)) {
0109         io_tlb_nslabs = simple_strtoul(str, &str, 0);
0110         /* avoid tail segment of size < IO_TLB_SEGSIZE */
0111         io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
0112     }
0113     if (*str == ',')
0114         ++str;
0115     if (!strcmp(str, "force")) {
0116         swiotlb_force = SWIOTLB_FORCE;
0117     } else if (!strcmp(str, "noforce")) {
0118         swiotlb_force = SWIOTLB_NO_FORCE;
0119         io_tlb_nslabs = 1;
0120     }
0121 
0122     return 0;
0123 }
0124 early_param("swiotlb", setup_io_tlb_npages);
0125 /* make io_tlb_overflow tunable too? */
0126 
0127 unsigned long swiotlb_nr_tbl(void)
0128 {
0129     return io_tlb_nslabs;
0130 }
0131 EXPORT_SYMBOL_GPL(swiotlb_nr_tbl);
0132 
0133 unsigned int swiotlb_max_segment(void)
0134 {
0135     return max_segment;
0136 }
0137 EXPORT_SYMBOL_GPL(swiotlb_max_segment);
0138 
0139 void swiotlb_set_max_segment(unsigned int val)
0140 {
0141     if (swiotlb_force == SWIOTLB_FORCE)
0142         max_segment = 1;
0143     else
0144         max_segment = rounddown(val, PAGE_SIZE);
0145 }
0146 
0147 /* default to 64MB */
0148 #define IO_TLB_DEFAULT_SIZE (64UL<<20)
0149 unsigned long swiotlb_size_or_default(void)
0150 {
0151     unsigned long size;
0152 
0153     size = io_tlb_nslabs << IO_TLB_SHIFT;
0154 
0155     return size ? size : (IO_TLB_DEFAULT_SIZE);
0156 }
0157 
0158 /* Note that this doesn't work with highmem page */
0159 static dma_addr_t swiotlb_virt_to_bus(struct device *hwdev,
0160                       volatile void *address)
0161 {
0162     return phys_to_dma(hwdev, virt_to_phys(address));
0163 }
0164 
0165 static bool no_iotlb_memory;
0166 
0167 void swiotlb_print_info(void)
0168 {
0169     unsigned long bytes = io_tlb_nslabs << IO_TLB_SHIFT;
0170     unsigned char *vstart, *vend;
0171 
0172     if (no_iotlb_memory) {
0173         pr_warn("software IO TLB: No low mem\n");
0174         return;
0175     }
0176 
0177     vstart = phys_to_virt(io_tlb_start);
0178     vend = phys_to_virt(io_tlb_end);
0179 
0180     printk(KERN_INFO "software IO TLB [mem %#010llx-%#010llx] (%luMB) mapped at [%p-%p]\n",
0181            (unsigned long long)io_tlb_start,
0182            (unsigned long long)io_tlb_end,
0183            bytes >> 20, vstart, vend - 1);
0184 }
0185 
0186 int __init swiotlb_init_with_tbl(char *tlb, unsigned long nslabs, int verbose)
0187 {
0188     void *v_overflow_buffer;
0189     unsigned long i, bytes;
0190 
0191     bytes = nslabs << IO_TLB_SHIFT;
0192 
0193     io_tlb_nslabs = nslabs;
0194     io_tlb_start = __pa(tlb);
0195     io_tlb_end = io_tlb_start + bytes;
0196 
0197     /*
0198      * Get the overflow emergency buffer
0199      */
0200     v_overflow_buffer = memblock_virt_alloc_low_nopanic(
0201                         PAGE_ALIGN(io_tlb_overflow),
0202                         PAGE_SIZE);
0203     if (!v_overflow_buffer)
0204         return -ENOMEM;
0205 
0206     io_tlb_overflow_buffer = __pa(v_overflow_buffer);
0207 
0208     /*
0209      * Allocate and initialize the free list array.  This array is used
0210      * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
0211      * between io_tlb_start and io_tlb_end.
0212      */
0213     io_tlb_list = memblock_virt_alloc(
0214                 PAGE_ALIGN(io_tlb_nslabs * sizeof(int)),
0215                 PAGE_SIZE);
0216     io_tlb_orig_addr = memblock_virt_alloc(
0217                 PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)),
0218                 PAGE_SIZE);
0219     for (i = 0; i < io_tlb_nslabs; i++) {
0220         io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE);
0221         io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
0222     }
0223     io_tlb_index = 0;
0224 
0225     if (verbose)
0226         swiotlb_print_info();
0227 
0228     swiotlb_set_max_segment(io_tlb_nslabs << IO_TLB_SHIFT);
0229     return 0;
0230 }
0231 
0232 /*
0233  * Statically reserve bounce buffer space and initialize bounce buffer data
0234  * structures for the software IO TLB used to implement the DMA API.
0235  */
0236 void  __init
0237 swiotlb_init(int verbose)
0238 {
0239     size_t default_size = IO_TLB_DEFAULT_SIZE;
0240     unsigned char *vstart;
0241     unsigned long bytes;
0242 
0243     if (!io_tlb_nslabs) {
0244         io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
0245         io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
0246     }
0247 
0248     bytes = io_tlb_nslabs << IO_TLB_SHIFT;
0249 
0250     /* Get IO TLB memory from the low pages */
0251     vstart = memblock_virt_alloc_low_nopanic(PAGE_ALIGN(bytes), PAGE_SIZE);
0252     if (vstart && !swiotlb_init_with_tbl(vstart, io_tlb_nslabs, verbose))
0253         return;
0254 
0255     if (io_tlb_start)
0256         memblock_free_early(io_tlb_start,
0257                     PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
0258     pr_warn("Cannot allocate SWIOTLB buffer");
0259     no_iotlb_memory = true;
0260 }
0261 
0262 /*
0263  * Systems with larger DMA zones (those that don't support ISA) can
0264  * initialize the swiotlb later using the slab allocator if needed.
0265  * This should be just like above, but with some error catching.
0266  */
0267 int
0268 swiotlb_late_init_with_default_size(size_t default_size)
0269 {
0270     unsigned long bytes, req_nslabs = io_tlb_nslabs;
0271     unsigned char *vstart = NULL;
0272     unsigned int order;
0273     int rc = 0;
0274 
0275     if (!io_tlb_nslabs) {
0276         io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
0277         io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
0278     }
0279 
0280     /*
0281      * Get IO TLB memory from the low pages
0282      */
0283     order = get_order(io_tlb_nslabs << IO_TLB_SHIFT);
0284     io_tlb_nslabs = SLABS_PER_PAGE << order;
0285     bytes = io_tlb_nslabs << IO_TLB_SHIFT;
0286 
0287     while ((SLABS_PER_PAGE << order) > IO_TLB_MIN_SLABS) {
0288         vstart = (void *)__get_free_pages(GFP_DMA | __GFP_NOWARN,
0289                           order);
0290         if (vstart)
0291             break;
0292         order--;
0293     }
0294 
0295     if (!vstart) {
0296         io_tlb_nslabs = req_nslabs;
0297         return -ENOMEM;
0298     }
0299     if (order != get_order(bytes)) {
0300         printk(KERN_WARNING "Warning: only able to allocate %ld MB "
0301                "for software IO TLB\n", (PAGE_SIZE << order) >> 20);
0302         io_tlb_nslabs = SLABS_PER_PAGE << order;
0303     }
0304     rc = swiotlb_late_init_with_tbl(vstart, io_tlb_nslabs);
0305     if (rc)
0306         free_pages((unsigned long)vstart, order);
0307 
0308     return rc;
0309 }
0310 
0311 int
0312 swiotlb_late_init_with_tbl(char *tlb, unsigned long nslabs)
0313 {
0314     unsigned long i, bytes;
0315     unsigned char *v_overflow_buffer;
0316 
0317     bytes = nslabs << IO_TLB_SHIFT;
0318 
0319     io_tlb_nslabs = nslabs;
0320     io_tlb_start = virt_to_phys(tlb);
0321     io_tlb_end = io_tlb_start + bytes;
0322 
0323     memset(tlb, 0, bytes);
0324 
0325     /*
0326      * Get the overflow emergency buffer
0327      */
0328     v_overflow_buffer = (void *)__get_free_pages(GFP_DMA,
0329                              get_order(io_tlb_overflow));
0330     if (!v_overflow_buffer)
0331         goto cleanup2;
0332 
0333     io_tlb_overflow_buffer = virt_to_phys(v_overflow_buffer);
0334 
0335     /*
0336      * Allocate and initialize the free list array.  This array is used
0337      * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
0338      * between io_tlb_start and io_tlb_end.
0339      */
0340     io_tlb_list = (unsigned int *)__get_free_pages(GFP_KERNEL,
0341                                   get_order(io_tlb_nslabs * sizeof(int)));
0342     if (!io_tlb_list)
0343         goto cleanup3;
0344 
0345     io_tlb_orig_addr = (phys_addr_t *)
0346         __get_free_pages(GFP_KERNEL,
0347                  get_order(io_tlb_nslabs *
0348                        sizeof(phys_addr_t)));
0349     if (!io_tlb_orig_addr)
0350         goto cleanup4;
0351 
0352     for (i = 0; i < io_tlb_nslabs; i++) {
0353         io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE);
0354         io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
0355     }
0356     io_tlb_index = 0;
0357 
0358     swiotlb_print_info();
0359 
0360     late_alloc = 1;
0361 
0362     swiotlb_set_max_segment(io_tlb_nslabs << IO_TLB_SHIFT);
0363 
0364     return 0;
0365 
0366 cleanup4:
0367     free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
0368                                                      sizeof(int)));
0369     io_tlb_list = NULL;
0370 cleanup3:
0371     free_pages((unsigned long)v_overflow_buffer,
0372            get_order(io_tlb_overflow));
0373     io_tlb_overflow_buffer = 0;
0374 cleanup2:
0375     io_tlb_end = 0;
0376     io_tlb_start = 0;
0377     io_tlb_nslabs = 0;
0378     max_segment = 0;
0379     return -ENOMEM;
0380 }
0381 
0382 void __init swiotlb_free(void)
0383 {
0384     if (!io_tlb_orig_addr)
0385         return;
0386 
0387     if (late_alloc) {
0388         free_pages((unsigned long)phys_to_virt(io_tlb_overflow_buffer),
0389                get_order(io_tlb_overflow));
0390         free_pages((unsigned long)io_tlb_orig_addr,
0391                get_order(io_tlb_nslabs * sizeof(phys_addr_t)));
0392         free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
0393                                  sizeof(int)));
0394         free_pages((unsigned long)phys_to_virt(io_tlb_start),
0395                get_order(io_tlb_nslabs << IO_TLB_SHIFT));
0396     } else {
0397         memblock_free_late(io_tlb_overflow_buffer,
0398                    PAGE_ALIGN(io_tlb_overflow));
0399         memblock_free_late(__pa(io_tlb_orig_addr),
0400                    PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)));
0401         memblock_free_late(__pa(io_tlb_list),
0402                    PAGE_ALIGN(io_tlb_nslabs * sizeof(int)));
0403         memblock_free_late(io_tlb_start,
0404                    PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
0405     }
0406     io_tlb_nslabs = 0;
0407     max_segment = 0;
0408 }
0409 
0410 int is_swiotlb_buffer(phys_addr_t paddr)
0411 {
0412     return paddr >= io_tlb_start && paddr < io_tlb_end;
0413 }
0414 
0415 /*
0416  * Bounce: copy the swiotlb buffer back to the original dma location
0417  */
0418 static void swiotlb_bounce(phys_addr_t orig_addr, phys_addr_t tlb_addr,
0419                size_t size, enum dma_data_direction dir)
0420 {
0421     unsigned long pfn = PFN_DOWN(orig_addr);
0422     unsigned char *vaddr = phys_to_virt(tlb_addr);
0423 
0424     if (PageHighMem(pfn_to_page(pfn))) {
0425         /* The buffer does not have a mapping.  Map it in and copy */
0426         unsigned int offset = orig_addr & ~PAGE_MASK;
0427         char *buffer;
0428         unsigned int sz = 0;
0429         unsigned long flags;
0430 
0431         while (size) {
0432             sz = min_t(size_t, PAGE_SIZE - offset, size);
0433 
0434             local_irq_save(flags);
0435             buffer = kmap_atomic(pfn_to_page(pfn));
0436             if (dir == DMA_TO_DEVICE)
0437                 memcpy(vaddr, buffer + offset, sz);
0438             else
0439                 memcpy(buffer + offset, vaddr, sz);
0440             kunmap_atomic(buffer);
0441             local_irq_restore(flags);
0442 
0443             size -= sz;
0444             pfn++;
0445             vaddr += sz;
0446             offset = 0;
0447         }
0448     } else if (dir == DMA_TO_DEVICE) {
0449         memcpy(vaddr, phys_to_virt(orig_addr), size);
0450     } else {
0451         memcpy(phys_to_virt(orig_addr), vaddr, size);
0452     }
0453 }
0454 
0455 phys_addr_t swiotlb_tbl_map_single(struct device *hwdev,
0456                    dma_addr_t tbl_dma_addr,
0457                    phys_addr_t orig_addr, size_t size,
0458                    enum dma_data_direction dir,
0459                    unsigned long attrs)
0460 {
0461     unsigned long flags;
0462     phys_addr_t tlb_addr;
0463     unsigned int nslots, stride, index, wrap;
0464     int i;
0465     unsigned long mask;
0466     unsigned long offset_slots;
0467     unsigned long max_slots;
0468 
0469     if (no_iotlb_memory)
0470         panic("Can not allocate SWIOTLB buffer earlier and can't now provide you with the DMA bounce buffer");
0471 
0472     mask = dma_get_seg_boundary(hwdev);
0473 
0474     tbl_dma_addr &= mask;
0475 
0476     offset_slots = ALIGN(tbl_dma_addr, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
0477 
0478     /*
0479      * Carefully handle integer overflow which can occur when mask == ~0UL.
0480      */
0481     max_slots = mask + 1
0482             ? ALIGN(mask + 1, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT
0483             : 1UL << (BITS_PER_LONG - IO_TLB_SHIFT);
0484 
0485     /*
0486      * For mappings greater than or equal to a page, we limit the stride
0487      * (and hence alignment) to a page size.
0488      */
0489     nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
0490     if (size >= PAGE_SIZE)
0491         stride = (1 << (PAGE_SHIFT - IO_TLB_SHIFT));
0492     else
0493         stride = 1;
0494 
0495     BUG_ON(!nslots);
0496 
0497     /*
0498      * Find suitable number of IO TLB entries size that will fit this
0499      * request and allocate a buffer from that IO TLB pool.
0500      */
0501     spin_lock_irqsave(&io_tlb_lock, flags);
0502     index = ALIGN(io_tlb_index, stride);
0503     if (index >= io_tlb_nslabs)
0504         index = 0;
0505     wrap = index;
0506 
0507     do {
0508         while (iommu_is_span_boundary(index, nslots, offset_slots,
0509                           max_slots)) {
0510             index += stride;
0511             if (index >= io_tlb_nslabs)
0512                 index = 0;
0513             if (index == wrap)
0514                 goto not_found;
0515         }
0516 
0517         /*
0518          * If we find a slot that indicates we have 'nslots' number of
0519          * contiguous buffers, we allocate the buffers from that slot
0520          * and mark the entries as '0' indicating unavailable.
0521          */
0522         if (io_tlb_list[index] >= nslots) {
0523             int count = 0;
0524 
0525             for (i = index; i < (int) (index + nslots); i++)
0526                 io_tlb_list[i] = 0;
0527             for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE - 1) && io_tlb_list[i]; i--)
0528                 io_tlb_list[i] = ++count;
0529             tlb_addr = io_tlb_start + (index << IO_TLB_SHIFT);
0530 
0531             /*
0532              * Update the indices to avoid searching in the next
0533              * round.
0534              */
0535             io_tlb_index = ((index + nslots) < io_tlb_nslabs
0536                     ? (index + nslots) : 0);
0537 
0538             goto found;
0539         }
0540         index += stride;
0541         if (index >= io_tlb_nslabs)
0542             index = 0;
0543     } while (index != wrap);
0544 
0545 not_found:
0546     spin_unlock_irqrestore(&io_tlb_lock, flags);
0547     if (printk_ratelimit())
0548         dev_warn(hwdev, "swiotlb buffer is full (sz: %zd bytes)\n", size);
0549     return SWIOTLB_MAP_ERROR;
0550 found:
0551     spin_unlock_irqrestore(&io_tlb_lock, flags);
0552 
0553     /*
0554      * Save away the mapping from the original address to the DMA address.
0555      * This is needed when we sync the memory.  Then we sync the buffer if
0556      * needed.
0557      */
0558     for (i = 0; i < nslots; i++)
0559         io_tlb_orig_addr[index+i] = orig_addr + (i << IO_TLB_SHIFT);
0560     if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
0561         (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL))
0562         swiotlb_bounce(orig_addr, tlb_addr, size, DMA_TO_DEVICE);
0563 
0564     return tlb_addr;
0565 }
0566 EXPORT_SYMBOL_GPL(swiotlb_tbl_map_single);
0567 
0568 /*
0569  * Allocates bounce buffer and returns its kernel virtual address.
0570  */
0571 
0572 static phys_addr_t
0573 map_single(struct device *hwdev, phys_addr_t phys, size_t size,
0574        enum dma_data_direction dir, unsigned long attrs)
0575 {
0576     dma_addr_t start_dma_addr;
0577 
0578     if (swiotlb_force == SWIOTLB_NO_FORCE) {
0579         dev_warn_ratelimited(hwdev, "Cannot do DMA to address %pa\n",
0580                      &phys);
0581         return SWIOTLB_MAP_ERROR;
0582     }
0583 
0584     start_dma_addr = phys_to_dma(hwdev, io_tlb_start);
0585     return swiotlb_tbl_map_single(hwdev, start_dma_addr, phys, size,
0586                       dir, attrs);
0587 }
0588 
0589 /*
0590  * dma_addr is the kernel virtual address of the bounce buffer to unmap.
0591  */
0592 void swiotlb_tbl_unmap_single(struct device *hwdev, phys_addr_t tlb_addr,
0593                   size_t size, enum dma_data_direction dir,
0594                   unsigned long attrs)
0595 {
0596     unsigned long flags;
0597     int i, count, nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
0598     int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT;
0599     phys_addr_t orig_addr = io_tlb_orig_addr[index];
0600 
0601     /*
0602      * First, sync the memory before unmapping the entry
0603      */
0604     if (orig_addr != INVALID_PHYS_ADDR &&
0605         !(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
0606         ((dir == DMA_FROM_DEVICE) || (dir == DMA_BIDIRECTIONAL)))
0607         swiotlb_bounce(orig_addr, tlb_addr, size, DMA_FROM_DEVICE);
0608 
0609     /*
0610      * Return the buffer to the free list by setting the corresponding
0611      * entries to indicate the number of contiguous entries available.
0612      * While returning the entries to the free list, we merge the entries
0613      * with slots below and above the pool being returned.
0614      */
0615     spin_lock_irqsave(&io_tlb_lock, flags);
0616     {
0617         count = ((index + nslots) < ALIGN(index + 1, IO_TLB_SEGSIZE) ?
0618              io_tlb_list[index + nslots] : 0);
0619         /*
0620          * Step 1: return the slots to the free list, merging the
0621          * slots with superceeding slots
0622          */
0623         for (i = index + nslots - 1; i >= index; i--) {
0624             io_tlb_list[i] = ++count;
0625             io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
0626         }
0627         /*
0628          * Step 2: merge the returned slots with the preceding slots,
0629          * if available (non zero)
0630          */
0631         for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE -1) && io_tlb_list[i]; i--)
0632             io_tlb_list[i] = ++count;
0633     }
0634     spin_unlock_irqrestore(&io_tlb_lock, flags);
0635 }
0636 EXPORT_SYMBOL_GPL(swiotlb_tbl_unmap_single);
0637 
0638 void swiotlb_tbl_sync_single(struct device *hwdev, phys_addr_t tlb_addr,
0639                  size_t size, enum dma_data_direction dir,
0640                  enum dma_sync_target target)
0641 {
0642     int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT;
0643     phys_addr_t orig_addr = io_tlb_orig_addr[index];
0644 
0645     if (orig_addr == INVALID_PHYS_ADDR)
0646         return;
0647     orig_addr += (unsigned long)tlb_addr & ((1 << IO_TLB_SHIFT) - 1);
0648 
0649     switch (target) {
0650     case SYNC_FOR_CPU:
0651         if (likely(dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL))
0652             swiotlb_bounce(orig_addr, tlb_addr,
0653                        size, DMA_FROM_DEVICE);
0654         else
0655             BUG_ON(dir != DMA_TO_DEVICE);
0656         break;
0657     case SYNC_FOR_DEVICE:
0658         if (likely(dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL))
0659             swiotlb_bounce(orig_addr, tlb_addr,
0660                        size, DMA_TO_DEVICE);
0661         else
0662             BUG_ON(dir != DMA_FROM_DEVICE);
0663         break;
0664     default:
0665         BUG();
0666     }
0667 }
0668 EXPORT_SYMBOL_GPL(swiotlb_tbl_sync_single);
0669 
0670 void *
0671 swiotlb_alloc_coherent(struct device *hwdev, size_t size,
0672                dma_addr_t *dma_handle, gfp_t flags)
0673 {
0674     dma_addr_t dev_addr;
0675     void *ret;
0676     int order = get_order(size);
0677     u64 dma_mask = DMA_BIT_MASK(32);
0678 
0679     if (hwdev && hwdev->coherent_dma_mask)
0680         dma_mask = hwdev->coherent_dma_mask;
0681 
0682     ret = (void *)__get_free_pages(flags, order);
0683     if (ret) {
0684         dev_addr = swiotlb_virt_to_bus(hwdev, ret);
0685         if (dev_addr + size - 1 > dma_mask) {
0686             /*
0687              * The allocated memory isn't reachable by the device.
0688              */
0689             free_pages((unsigned long) ret, order);
0690             ret = NULL;
0691         }
0692     }
0693     if (!ret) {
0694         /*
0695          * We are either out of memory or the device can't DMA to
0696          * GFP_DMA memory; fall back on map_single(), which
0697          * will grab memory from the lowest available address range.
0698          */
0699         phys_addr_t paddr = map_single(hwdev, 0, size,
0700                            DMA_FROM_DEVICE, 0);
0701         if (paddr == SWIOTLB_MAP_ERROR)
0702             goto err_warn;
0703 
0704         ret = phys_to_virt(paddr);
0705         dev_addr = phys_to_dma(hwdev, paddr);
0706 
0707         /* Confirm address can be DMA'd by device */
0708         if (dev_addr + size - 1 > dma_mask) {
0709             printk("hwdev DMA mask = 0x%016Lx, dev_addr = 0x%016Lx\n",
0710                    (unsigned long long)dma_mask,
0711                    (unsigned long long)dev_addr);
0712 
0713             /*
0714              * DMA_TO_DEVICE to avoid memcpy in unmap_single.
0715              * The DMA_ATTR_SKIP_CPU_SYNC is optional.
0716              */
0717             swiotlb_tbl_unmap_single(hwdev, paddr,
0718                          size, DMA_TO_DEVICE,
0719                          DMA_ATTR_SKIP_CPU_SYNC);
0720             goto err_warn;
0721         }
0722     }
0723 
0724     *dma_handle = dev_addr;
0725     memset(ret, 0, size);
0726 
0727     return ret;
0728 
0729 err_warn:
0730     pr_warn("swiotlb: coherent allocation failed for device %s size=%zu\n",
0731         dev_name(hwdev), size);
0732     dump_stack();
0733 
0734     return NULL;
0735 }
0736 EXPORT_SYMBOL(swiotlb_alloc_coherent);
0737 
0738 void
0739 swiotlb_free_coherent(struct device *hwdev, size_t size, void *vaddr,
0740               dma_addr_t dev_addr)
0741 {
0742     phys_addr_t paddr = dma_to_phys(hwdev, dev_addr);
0743 
0744     WARN_ON(irqs_disabled());
0745     if (!is_swiotlb_buffer(paddr))
0746         free_pages((unsigned long)vaddr, get_order(size));
0747     else
0748         /*
0749          * DMA_TO_DEVICE to avoid memcpy in swiotlb_tbl_unmap_single.
0750          * DMA_ATTR_SKIP_CPU_SYNC is optional.
0751          */
0752         swiotlb_tbl_unmap_single(hwdev, paddr, size, DMA_TO_DEVICE,
0753                      DMA_ATTR_SKIP_CPU_SYNC);
0754 }
0755 EXPORT_SYMBOL(swiotlb_free_coherent);
0756 
0757 static void
0758 swiotlb_full(struct device *dev, size_t size, enum dma_data_direction dir,
0759          int do_panic)
0760 {
0761     if (swiotlb_force == SWIOTLB_NO_FORCE)
0762         return;
0763 
0764     /*
0765      * Ran out of IOMMU space for this operation. This is very bad.
0766      * Unfortunately the drivers cannot handle this operation properly.
0767      * unless they check for dma_mapping_error (most don't)
0768      * When the mapping is small enough return a static buffer to limit
0769      * the damage, or panic when the transfer is too big.
0770      */
0771     dev_err_ratelimited(dev, "DMA: Out of SW-IOMMU space for %zu bytes\n",
0772                 size);
0773 
0774     if (size <= io_tlb_overflow || !do_panic)
0775         return;
0776 
0777     if (dir == DMA_BIDIRECTIONAL)
0778         panic("DMA: Random memory could be DMA accessed\n");
0779     if (dir == DMA_FROM_DEVICE)
0780         panic("DMA: Random memory could be DMA written\n");
0781     if (dir == DMA_TO_DEVICE)
0782         panic("DMA: Random memory could be DMA read\n");
0783 }
0784 
0785 /*
0786  * Map a single buffer of the indicated size for DMA in streaming mode.  The
0787  * physical address to use is returned.
0788  *
0789  * Once the device is given the dma address, the device owns this memory until
0790  * either swiotlb_unmap_page or swiotlb_dma_sync_single is performed.
0791  */
0792 dma_addr_t swiotlb_map_page(struct device *dev, struct page *page,
0793                 unsigned long offset, size_t size,
0794                 enum dma_data_direction dir,
0795                 unsigned long attrs)
0796 {
0797     phys_addr_t map, phys = page_to_phys(page) + offset;
0798     dma_addr_t dev_addr = phys_to_dma(dev, phys);
0799 
0800     BUG_ON(dir == DMA_NONE);
0801     /*
0802      * If the address happens to be in the device's DMA window,
0803      * we can safely return the device addr and not worry about bounce
0804      * buffering it.
0805      */
0806     if (dma_capable(dev, dev_addr, size) && swiotlb_force != SWIOTLB_FORCE)
0807         return dev_addr;
0808 
0809     trace_swiotlb_bounced(dev, dev_addr, size, swiotlb_force);
0810 
0811     /* Oh well, have to allocate and map a bounce buffer. */
0812     map = map_single(dev, phys, size, dir, attrs);
0813     if (map == SWIOTLB_MAP_ERROR) {
0814         swiotlb_full(dev, size, dir, 1);
0815         return phys_to_dma(dev, io_tlb_overflow_buffer);
0816     }
0817 
0818     dev_addr = phys_to_dma(dev, map);
0819 
0820     /* Ensure that the address returned is DMA'ble */
0821     if (dma_capable(dev, dev_addr, size))
0822         return dev_addr;
0823 
0824     attrs |= DMA_ATTR_SKIP_CPU_SYNC;
0825     swiotlb_tbl_unmap_single(dev, map, size, dir, attrs);
0826 
0827     return phys_to_dma(dev, io_tlb_overflow_buffer);
0828 }
0829 EXPORT_SYMBOL_GPL(swiotlb_map_page);
0830 
0831 /*
0832  * Unmap a single streaming mode DMA translation.  The dma_addr and size must
0833  * match what was provided for in a previous swiotlb_map_page call.  All
0834  * other usages are undefined.
0835  *
0836  * After this call, reads by the cpu to the buffer are guaranteed to see
0837  * whatever the device wrote there.
0838  */
0839 static void unmap_single(struct device *hwdev, dma_addr_t dev_addr,
0840              size_t size, enum dma_data_direction dir,
0841              unsigned long attrs)
0842 {
0843     phys_addr_t paddr = dma_to_phys(hwdev, dev_addr);
0844 
0845     BUG_ON(dir == DMA_NONE);
0846 
0847     if (is_swiotlb_buffer(paddr)) {
0848         swiotlb_tbl_unmap_single(hwdev, paddr, size, dir, attrs);
0849         return;
0850     }
0851 
0852     if (dir != DMA_FROM_DEVICE)
0853         return;
0854 
0855     /*
0856      * phys_to_virt doesn't work with hihgmem page but we could
0857      * call dma_mark_clean() with hihgmem page here. However, we
0858      * are fine since dma_mark_clean() is null on POWERPC. We can
0859      * make dma_mark_clean() take a physical address if necessary.
0860      */
0861     dma_mark_clean(phys_to_virt(paddr), size);
0862 }
0863 
0864 void swiotlb_unmap_page(struct device *hwdev, dma_addr_t dev_addr,
0865             size_t size, enum dma_data_direction dir,
0866             unsigned long attrs)
0867 {
0868     unmap_single(hwdev, dev_addr, size, dir, attrs);
0869 }
0870 EXPORT_SYMBOL_GPL(swiotlb_unmap_page);
0871 
0872 /*
0873  * Make physical memory consistent for a single streaming mode DMA translation
0874  * after a transfer.
0875  *
0876  * If you perform a swiotlb_map_page() but wish to interrogate the buffer
0877  * using the cpu, yet do not wish to teardown the dma mapping, you must
0878  * call this function before doing so.  At the next point you give the dma
0879  * address back to the card, you must first perform a
0880  * swiotlb_dma_sync_for_device, and then the device again owns the buffer
0881  */
0882 static void
0883 swiotlb_sync_single(struct device *hwdev, dma_addr_t dev_addr,
0884             size_t size, enum dma_data_direction dir,
0885             enum dma_sync_target target)
0886 {
0887     phys_addr_t paddr = dma_to_phys(hwdev, dev_addr);
0888 
0889     BUG_ON(dir == DMA_NONE);
0890 
0891     if (is_swiotlb_buffer(paddr)) {
0892         swiotlb_tbl_sync_single(hwdev, paddr, size, dir, target);
0893         return;
0894     }
0895 
0896     if (dir != DMA_FROM_DEVICE)
0897         return;
0898 
0899     dma_mark_clean(phys_to_virt(paddr), size);
0900 }
0901 
0902 void
0903 swiotlb_sync_single_for_cpu(struct device *hwdev, dma_addr_t dev_addr,
0904                 size_t size, enum dma_data_direction dir)
0905 {
0906     swiotlb_sync_single(hwdev, dev_addr, size, dir, SYNC_FOR_CPU);
0907 }
0908 EXPORT_SYMBOL(swiotlb_sync_single_for_cpu);
0909 
0910 void
0911 swiotlb_sync_single_for_device(struct device *hwdev, dma_addr_t dev_addr,
0912                    size_t size, enum dma_data_direction dir)
0913 {
0914     swiotlb_sync_single(hwdev, dev_addr, size, dir, SYNC_FOR_DEVICE);
0915 }
0916 EXPORT_SYMBOL(swiotlb_sync_single_for_device);
0917 
0918 /*
0919  * Map a set of buffers described by scatterlist in streaming mode for DMA.
0920  * This is the scatter-gather version of the above swiotlb_map_page
0921  * interface.  Here the scatter gather list elements are each tagged with the
0922  * appropriate dma address and length.  They are obtained via
0923  * sg_dma_{address,length}(SG).
0924  *
0925  * NOTE: An implementation may be able to use a smaller number of
0926  *       DMA address/length pairs than there are SG table elements.
0927  *       (for example via virtual mapping capabilities)
0928  *       The routine returns the number of addr/length pairs actually
0929  *       used, at most nents.
0930  *
0931  * Device ownership issues as mentioned above for swiotlb_map_page are the
0932  * same here.
0933  */
0934 int
0935 swiotlb_map_sg_attrs(struct device *hwdev, struct scatterlist *sgl, int nelems,
0936              enum dma_data_direction dir, unsigned long attrs)
0937 {
0938     struct scatterlist *sg;
0939     int i;
0940 
0941     BUG_ON(dir == DMA_NONE);
0942 
0943     for_each_sg(sgl, sg, nelems, i) {
0944         phys_addr_t paddr = sg_phys(sg);
0945         dma_addr_t dev_addr = phys_to_dma(hwdev, paddr);
0946 
0947         if (swiotlb_force == SWIOTLB_FORCE ||
0948             !dma_capable(hwdev, dev_addr, sg->length)) {
0949             phys_addr_t map = map_single(hwdev, sg_phys(sg),
0950                              sg->length, dir, attrs);
0951             if (map == SWIOTLB_MAP_ERROR) {
0952                 /* Don't panic here, we expect map_sg users
0953                    to do proper error handling. */
0954                 swiotlb_full(hwdev, sg->length, dir, 0);
0955                 attrs |= DMA_ATTR_SKIP_CPU_SYNC;
0956                 swiotlb_unmap_sg_attrs(hwdev, sgl, i, dir,
0957                                attrs);
0958                 sg_dma_len(sgl) = 0;
0959                 return 0;
0960             }
0961             sg->dma_address = phys_to_dma(hwdev, map);
0962         } else
0963             sg->dma_address = dev_addr;
0964         sg_dma_len(sg) = sg->length;
0965     }
0966     return nelems;
0967 }
0968 EXPORT_SYMBOL(swiotlb_map_sg_attrs);
0969 
0970 /*
0971  * Unmap a set of streaming mode DMA translations.  Again, cpu read rules
0972  * concerning calls here are the same as for swiotlb_unmap_page() above.
0973  */
0974 void
0975 swiotlb_unmap_sg_attrs(struct device *hwdev, struct scatterlist *sgl,
0976                int nelems, enum dma_data_direction dir,
0977                unsigned long attrs)
0978 {
0979     struct scatterlist *sg;
0980     int i;
0981 
0982     BUG_ON(dir == DMA_NONE);
0983 
0984     for_each_sg(sgl, sg, nelems, i)
0985         unmap_single(hwdev, sg->dma_address, sg_dma_len(sg), dir,
0986                  attrs);
0987 }
0988 EXPORT_SYMBOL(swiotlb_unmap_sg_attrs);
0989 
0990 /*
0991  * Make physical memory consistent for a set of streaming mode DMA translations
0992  * after a transfer.
0993  *
0994  * The same as swiotlb_sync_single_* but for a scatter-gather list, same rules
0995  * and usage.
0996  */
0997 static void
0998 swiotlb_sync_sg(struct device *hwdev, struct scatterlist *sgl,
0999         int nelems, enum dma_data_direction dir,
1000         enum dma_sync_target target)
1001 {
1002     struct scatterlist *sg;
1003     int i;
1004 
1005     for_each_sg(sgl, sg, nelems, i)
1006         swiotlb_sync_single(hwdev, sg->dma_address,
1007                     sg_dma_len(sg), dir, target);
1008 }
1009 
1010 void
1011 swiotlb_sync_sg_for_cpu(struct device *hwdev, struct scatterlist *sg,
1012             int nelems, enum dma_data_direction dir)
1013 {
1014     swiotlb_sync_sg(hwdev, sg, nelems, dir, SYNC_FOR_CPU);
1015 }
1016 EXPORT_SYMBOL(swiotlb_sync_sg_for_cpu);
1017 
1018 void
1019 swiotlb_sync_sg_for_device(struct device *hwdev, struct scatterlist *sg,
1020                int nelems, enum dma_data_direction dir)
1021 {
1022     swiotlb_sync_sg(hwdev, sg, nelems, dir, SYNC_FOR_DEVICE);
1023 }
1024 EXPORT_SYMBOL(swiotlb_sync_sg_for_device);
1025 
1026 int
1027 swiotlb_dma_mapping_error(struct device *hwdev, dma_addr_t dma_addr)
1028 {
1029     return (dma_addr == phys_to_dma(hwdev, io_tlb_overflow_buffer));
1030 }
1031 EXPORT_SYMBOL(swiotlb_dma_mapping_error);
1032 
1033 /*
1034  * Return whether the given device DMA address mask can be supported
1035  * properly.  For example, if your device can only drive the low 24-bits
1036  * during bus mastering, then you would pass 0x00ffffff as the mask to
1037  * this function.
1038  */
1039 int
1040 swiotlb_dma_supported(struct device *hwdev, u64 mask)
1041 {
1042     return phys_to_dma(hwdev, io_tlb_end - 1) <= mask;
1043 }
1044 EXPORT_SYMBOL(swiotlb_dma_supported);