2 * Dynamic DMA mapping support.
4 * This implementation is a fallback for platforms that do not support
5 * I/O TLBs (aka DMA address translation hardware).
6 * Copyright (C) 2000 Asit Mallick <Asit.K.Mallick@intel.com>
7 * Copyright (C) 2000 Goutham Rao <goutham.rao@intel.com>
8 * Copyright (C) 2000, 2003 Hewlett-Packard Co
9 * David Mosberger-Tang <davidm@hpl.hp.com>
11 * 03/05/07 davidm Switch from PCI-DMA to generic device DMA API.
12 * 00/12/13 davidm Rename to swiotlb.c and add mark_clean() to avoid
13 * unnecessary i-cache flushing.
14 * 04/07/.. ak Better overflow handling. Assorted fixes.
15 * 05/09/10 linville Add support for syncing ranges, support syncing for
16 * DMA_BIDIRECTIONAL mappings, miscellaneous cleanup.
17 * 08/12/11 beckyb Add highmem support
20 #define pr_fmt(fmt) "software IO TLB: " fmt
22 #include <linux/cache.h>
23 #include <linux/dma-direct.h>
25 #include <linux/export.h>
26 #include <linux/spinlock.h>
27 #include <linux/string.h>
28 #include <linux/swiotlb.h>
29 #include <linux/pfn.h>
30 #include <linux/types.h>
31 #include <linux/ctype.h>
32 #include <linux/highmem.h>
33 #include <linux/gfp.h>
34 #include <linux/scatterlist.h>
35 #include <linux/mem_encrypt.h>
36 #include <linux/set_memory.h>
37 #ifdef CONFIG_DEBUG_FS
38 #include <linux/debugfs.h>
44 #include <linux/init.h>
45 #include <linux/memblock.h>
46 #include <linux/iommu-helper.h>
48 #define CREATE_TRACE_POINTS
49 #include <trace/events/swiotlb.h>
51 #define OFFSET(val,align) ((unsigned long) \
52 ( (val) & ( (align) - 1)))
54 #define SLABS_PER_PAGE (1 << (PAGE_SHIFT - IO_TLB_SHIFT))
57 * Minimum IO TLB size to bother booting with. Systems with mainly
58 * 64bit capable cards will only lightly use the swiotlb. If we can't
59 * allocate a contiguous 1MB, we're probably in trouble anyway.
61 #define IO_TLB_MIN_SLABS ((1<<20) >> IO_TLB_SHIFT)
63 enum swiotlb_force swiotlb_force;
66 * Used to do a quick range check in swiotlb_tbl_unmap_single and
67 * swiotlb_tbl_sync_single_*, to see if the memory was in fact allocated by this
70 phys_addr_t io_tlb_start, io_tlb_end;
73 * The number of IO TLB blocks (in groups of 64) between io_tlb_start and
74 * io_tlb_end. This is command line adjustable via setup_io_tlb_npages.
76 static unsigned long io_tlb_nslabs;
79 * The number of used IO TLB block
81 static unsigned long io_tlb_used;
84 * This is a free list describing the number of free entries available from
87 static unsigned int *io_tlb_list;
88 static unsigned int io_tlb_index;
91 * Max segment that we can provide which (if pages are contingous) will
92 * not be bounced (unless SWIOTLB_FORCE is set).
94 unsigned int max_segment;
97 * We need to save away the original address corresponding to a mapped entry
98 * for the sync operations.
100 #define INVALID_PHYS_ADDR (~(phys_addr_t)0)
101 static phys_addr_t *io_tlb_orig_addr;
104 * Protect the above data structures in the map and unmap calls
106 static DEFINE_SPINLOCK(io_tlb_lock);
108 static int late_alloc;
111 setup_io_tlb_npages(char *str)
114 io_tlb_nslabs = simple_strtoul(str, &str, 0);
115 /* avoid tail segment of size < IO_TLB_SEGSIZE */
116 io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
120 if (!strcmp(str, "force")) {
121 swiotlb_force = SWIOTLB_FORCE;
122 } else if (!strcmp(str, "noforce")) {
123 swiotlb_force = SWIOTLB_NO_FORCE;
129 early_param("swiotlb", setup_io_tlb_npages);
131 unsigned long swiotlb_nr_tbl(void)
133 return io_tlb_nslabs;
135 EXPORT_SYMBOL_GPL(swiotlb_nr_tbl);
137 unsigned int swiotlb_max_segment(void)
141 EXPORT_SYMBOL_GPL(swiotlb_max_segment);
143 void swiotlb_set_max_segment(unsigned int val)
145 if (swiotlb_force == SWIOTLB_FORCE)
148 max_segment = rounddown(val, PAGE_SIZE);
151 /* default to 64MB */
152 #define IO_TLB_DEFAULT_SIZE (64UL<<20)
153 unsigned long swiotlb_size_or_default(void)
157 size = io_tlb_nslabs << IO_TLB_SHIFT;
159 return size ? size : (IO_TLB_DEFAULT_SIZE);
162 static bool no_iotlb_memory;
164 void swiotlb_print_info(void)
166 unsigned long bytes = io_tlb_nslabs << IO_TLB_SHIFT;
168 if (no_iotlb_memory) {
169 pr_warn("No low mem\n");
173 pr_info("mapped [mem %#010llx-%#010llx] (%luMB)\n",
174 (unsigned long long)io_tlb_start,
175 (unsigned long long)io_tlb_end,
180 * Early SWIOTLB allocation may be too early to allow an architecture to
181 * perform the desired operations. This function allows the architecture to
182 * call SWIOTLB when the operations are possible. It needs to be called
183 * before the SWIOTLB memory is used.
185 void __init swiotlb_update_mem_attributes(void)
190 if (no_iotlb_memory || late_alloc)
193 vaddr = phys_to_virt(io_tlb_start);
194 bytes = PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT);
195 set_memory_decrypted((unsigned long)vaddr, bytes >> PAGE_SHIFT);
196 memset(vaddr, 0, bytes);
199 int __init swiotlb_init_with_tbl(char *tlb, unsigned long nslabs, int verbose)
201 unsigned long i, bytes;
203 bytes = nslabs << IO_TLB_SHIFT;
205 io_tlb_nslabs = nslabs;
206 io_tlb_start = __pa(tlb);
207 io_tlb_end = io_tlb_start + bytes;
210 * Allocate and initialize the free list array. This array is used
211 * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
212 * between io_tlb_start and io_tlb_end.
214 io_tlb_list = memblock_alloc(
215 PAGE_ALIGN(io_tlb_nslabs * sizeof(int)),
217 io_tlb_orig_addr = memblock_alloc(
218 PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)),
220 for (i = 0; i < io_tlb_nslabs; i++) {
221 io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE);
222 io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
227 swiotlb_print_info();
229 swiotlb_set_max_segment(io_tlb_nslabs << IO_TLB_SHIFT);
234 * Statically reserve bounce buffer space and initialize bounce buffer data
235 * structures for the software IO TLB used to implement the DMA API.
238 swiotlb_init(int verbose)
240 size_t default_size = IO_TLB_DEFAULT_SIZE;
241 unsigned char *vstart;
244 if (!io_tlb_nslabs) {
245 io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
246 io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
249 bytes = io_tlb_nslabs << IO_TLB_SHIFT;
251 /* Get IO TLB memory from the low pages */
252 vstart = memblock_alloc_low_nopanic(PAGE_ALIGN(bytes), PAGE_SIZE);
253 if (vstart && !swiotlb_init_with_tbl(vstart, io_tlb_nslabs, verbose))
257 memblock_free_early(io_tlb_start,
258 PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
259 pr_warn("Cannot allocate buffer");
260 no_iotlb_memory = true;
264 * Systems with larger DMA zones (those that don't support ISA) can
265 * initialize the swiotlb later using the slab allocator if needed.
266 * This should be just like above, but with some error catching.
269 swiotlb_late_init_with_default_size(size_t default_size)
271 unsigned long bytes, req_nslabs = io_tlb_nslabs;
272 unsigned char *vstart = NULL;
276 if (!io_tlb_nslabs) {
277 io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
278 io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
282 * Get IO TLB memory from the low pages
284 order = get_order(io_tlb_nslabs << IO_TLB_SHIFT);
285 io_tlb_nslabs = SLABS_PER_PAGE << order;
286 bytes = io_tlb_nslabs << IO_TLB_SHIFT;
288 while ((SLABS_PER_PAGE << order) > IO_TLB_MIN_SLABS) {
289 vstart = (void *)__get_free_pages(GFP_DMA | __GFP_NOWARN,
297 io_tlb_nslabs = req_nslabs;
300 if (order != get_order(bytes)) {
301 pr_warn("only able to allocate %ld MB\n",
302 (PAGE_SIZE << order) >> 20);
303 io_tlb_nslabs = SLABS_PER_PAGE << order;
305 rc = swiotlb_late_init_with_tbl(vstart, io_tlb_nslabs);
307 free_pages((unsigned long)vstart, order);
313 swiotlb_late_init_with_tbl(char *tlb, unsigned long nslabs)
315 unsigned long i, bytes;
317 bytes = nslabs << IO_TLB_SHIFT;
319 io_tlb_nslabs = nslabs;
320 io_tlb_start = virt_to_phys(tlb);
321 io_tlb_end = io_tlb_start + bytes;
323 set_memory_decrypted((unsigned long)tlb, bytes >> PAGE_SHIFT);
324 memset(tlb, 0, bytes);
327 * Allocate and initialize the free list array. This array is used
328 * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
329 * between io_tlb_start and io_tlb_end.
331 io_tlb_list = (unsigned int *)__get_free_pages(GFP_KERNEL,
332 get_order(io_tlb_nslabs * sizeof(int)));
336 io_tlb_orig_addr = (phys_addr_t *)
337 __get_free_pages(GFP_KERNEL,
338 get_order(io_tlb_nslabs *
339 sizeof(phys_addr_t)));
340 if (!io_tlb_orig_addr)
343 for (i = 0; i < io_tlb_nslabs; i++) {
344 io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE);
345 io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
349 swiotlb_print_info();
353 swiotlb_set_max_segment(io_tlb_nslabs << IO_TLB_SHIFT);
358 free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
369 void __init swiotlb_exit(void)
371 if (!io_tlb_orig_addr)
375 free_pages((unsigned long)io_tlb_orig_addr,
376 get_order(io_tlb_nslabs * sizeof(phys_addr_t)));
377 free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
379 free_pages((unsigned long)phys_to_virt(io_tlb_start),
380 get_order(io_tlb_nslabs << IO_TLB_SHIFT));
382 memblock_free_late(__pa(io_tlb_orig_addr),
383 PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)));
384 memblock_free_late(__pa(io_tlb_list),
385 PAGE_ALIGN(io_tlb_nslabs * sizeof(int)));
386 memblock_free_late(io_tlb_start,
387 PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
396 * Bounce: copy the swiotlb buffer from or back to the original dma location
398 static void swiotlb_bounce(phys_addr_t orig_addr, phys_addr_t tlb_addr,
399 size_t size, enum dma_data_direction dir)
401 unsigned long pfn = PFN_DOWN(orig_addr);
402 unsigned char *vaddr = phys_to_virt(tlb_addr);
404 if (PageHighMem(pfn_to_page(pfn))) {
405 /* The buffer does not have a mapping. Map it in and copy */
406 unsigned int offset = orig_addr & ~PAGE_MASK;
412 sz = min_t(size_t, PAGE_SIZE - offset, size);
414 local_irq_save(flags);
415 buffer = kmap_atomic(pfn_to_page(pfn));
416 if (dir == DMA_TO_DEVICE)
417 memcpy(vaddr, buffer + offset, sz);
419 memcpy(buffer + offset, vaddr, sz);
420 kunmap_atomic(buffer);
421 local_irq_restore(flags);
428 } else if (dir == DMA_TO_DEVICE) {
429 memcpy(vaddr, phys_to_virt(orig_addr), size);
431 memcpy(phys_to_virt(orig_addr), vaddr, size);
435 phys_addr_t swiotlb_tbl_map_single(struct device *hwdev,
436 dma_addr_t tbl_dma_addr,
437 phys_addr_t orig_addr, size_t size,
438 enum dma_data_direction dir,
442 phys_addr_t tlb_addr;
443 unsigned int nslots, stride, index, wrap;
446 unsigned long offset_slots;
447 unsigned long max_slots;
450 panic("Can not allocate SWIOTLB buffer earlier and can't now provide you with the DMA bounce buffer");
452 if (mem_encrypt_active())
453 pr_warn_once("%s is active and system is using DMA bounce buffers\n",
454 sme_active() ? "SME" : "SEV");
456 mask = dma_get_seg_boundary(hwdev);
458 tbl_dma_addr &= mask;
460 offset_slots = ALIGN(tbl_dma_addr, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
463 * Carefully handle integer overflow which can occur when mask == ~0UL.
466 ? ALIGN(mask + 1, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT
467 : 1UL << (BITS_PER_LONG - IO_TLB_SHIFT);
470 * For mappings greater than or equal to a page, we limit the stride
471 * (and hence alignment) to a page size.
473 nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
474 if (size >= PAGE_SIZE)
475 stride = (1 << (PAGE_SHIFT - IO_TLB_SHIFT));
482 * Find suitable number of IO TLB entries size that will fit this
483 * request and allocate a buffer from that IO TLB pool.
485 spin_lock_irqsave(&io_tlb_lock, flags);
487 if (unlikely(nslots > io_tlb_nslabs - io_tlb_used))
490 index = ALIGN(io_tlb_index, stride);
491 if (index >= io_tlb_nslabs)
496 while (iommu_is_span_boundary(index, nslots, offset_slots,
499 if (index >= io_tlb_nslabs)
506 * If we find a slot that indicates we have 'nslots' number of
507 * contiguous buffers, we allocate the buffers from that slot
508 * and mark the entries as '0' indicating unavailable.
510 if (io_tlb_list[index] >= nslots) {
513 for (i = index; i < (int) (index + nslots); i++)
515 for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE - 1) && io_tlb_list[i]; i--)
516 io_tlb_list[i] = ++count;
517 tlb_addr = io_tlb_start + (index << IO_TLB_SHIFT);
520 * Update the indices to avoid searching in the next
523 io_tlb_index = ((index + nslots) < io_tlb_nslabs
524 ? (index + nslots) : 0);
529 if (index >= io_tlb_nslabs)
531 } while (index != wrap);
534 spin_unlock_irqrestore(&io_tlb_lock, flags);
535 if (!(attrs & DMA_ATTR_NO_WARN) && printk_ratelimit())
536 dev_warn(hwdev, "swiotlb buffer is full (sz: %zd bytes)\n", size);
537 return DMA_MAPPING_ERROR;
539 io_tlb_used += nslots;
540 spin_unlock_irqrestore(&io_tlb_lock, flags);
543 * Save away the mapping from the original address to the DMA address.
544 * This is needed when we sync the memory. Then we sync the buffer if
547 for (i = 0; i < nslots; i++)
548 io_tlb_orig_addr[index+i] = orig_addr + (i << IO_TLB_SHIFT);
549 if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
550 (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL))
551 swiotlb_bounce(orig_addr, tlb_addr, size, DMA_TO_DEVICE);
557 * tlb_addr is the physical address of the bounce buffer to unmap.
559 void swiotlb_tbl_unmap_single(struct device *hwdev, phys_addr_t tlb_addr,
560 size_t size, enum dma_data_direction dir,
564 int i, count, nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
565 int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT;
566 phys_addr_t orig_addr = io_tlb_orig_addr[index];
569 * First, sync the memory before unmapping the entry
571 if (orig_addr != INVALID_PHYS_ADDR &&
572 !(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
573 ((dir == DMA_FROM_DEVICE) || (dir == DMA_BIDIRECTIONAL)))
574 swiotlb_bounce(orig_addr, tlb_addr, size, DMA_FROM_DEVICE);
577 * Return the buffer to the free list by setting the corresponding
578 * entries to indicate the number of contiguous entries available.
579 * While returning the entries to the free list, we merge the entries
580 * with slots below and above the pool being returned.
582 spin_lock_irqsave(&io_tlb_lock, flags);
584 count = ((index + nslots) < ALIGN(index + 1, IO_TLB_SEGSIZE) ?
585 io_tlb_list[index + nslots] : 0);
587 * Step 1: return the slots to the free list, merging the
588 * slots with superceeding slots
590 for (i = index + nslots - 1; i >= index; i--) {
591 io_tlb_list[i] = ++count;
592 io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
595 * Step 2: merge the returned slots with the preceding slots,
596 * if available (non zero)
598 for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE -1) && io_tlb_list[i]; i--)
599 io_tlb_list[i] = ++count;
601 io_tlb_used -= nslots;
603 spin_unlock_irqrestore(&io_tlb_lock, flags);
606 void swiotlb_tbl_sync_single(struct device *hwdev, phys_addr_t tlb_addr,
607 size_t size, enum dma_data_direction dir,
608 enum dma_sync_target target)
610 int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT;
611 phys_addr_t orig_addr = io_tlb_orig_addr[index];
613 if (orig_addr == INVALID_PHYS_ADDR)
615 orig_addr += (unsigned long)tlb_addr & ((1 << IO_TLB_SHIFT) - 1);
619 if (likely(dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL))
620 swiotlb_bounce(orig_addr, tlb_addr,
621 size, DMA_FROM_DEVICE);
623 BUG_ON(dir != DMA_TO_DEVICE);
625 case SYNC_FOR_DEVICE:
626 if (likely(dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL))
627 swiotlb_bounce(orig_addr, tlb_addr,
628 size, DMA_TO_DEVICE);
630 BUG_ON(dir != DMA_FROM_DEVICE);
638 * Create a swiotlb mapping for the buffer at @phys, and in case of DMAing
639 * to the device copy the data into it as well.
641 bool swiotlb_map(struct device *dev, phys_addr_t *phys, dma_addr_t *dma_addr,
642 size_t size, enum dma_data_direction dir, unsigned long attrs)
644 trace_swiotlb_bounced(dev, *dma_addr, size, swiotlb_force);
646 if (unlikely(swiotlb_force == SWIOTLB_NO_FORCE)) {
647 dev_warn_ratelimited(dev,
648 "Cannot do DMA to address %pa\n", phys);
652 /* Oh well, have to allocate and map a bounce buffer. */
653 *phys = swiotlb_tbl_map_single(dev, __phys_to_dma(dev, io_tlb_start),
654 *phys, size, dir, attrs);
655 if (*phys == DMA_MAPPING_ERROR)
658 /* Ensure that the address returned is DMA'ble */
659 *dma_addr = __phys_to_dma(dev, *phys);
660 if (unlikely(!dma_capable(dev, *dma_addr, size))) {
661 swiotlb_tbl_unmap_single(dev, *phys, size, dir,
662 attrs | DMA_ATTR_SKIP_CPU_SYNC);
669 size_t swiotlb_max_mapping_size(struct device *dev)
671 return ((size_t)1 << IO_TLB_SHIFT) * IO_TLB_SEGSIZE;
674 bool is_swiotlb_active(void)
677 * When SWIOTLB is initialized, even if io_tlb_start points to physical
678 * address zero, io_tlb_end surely doesn't.
680 return io_tlb_end != 0;
683 #ifdef CONFIG_DEBUG_FS
685 static int __init swiotlb_create_debugfs(void)
687 struct dentry *d_swiotlb_usage;
690 d_swiotlb_usage = debugfs_create_dir("swiotlb", NULL);
692 if (!d_swiotlb_usage)
695 ent = debugfs_create_ulong("io_tlb_nslabs", 0400,
696 d_swiotlb_usage, &io_tlb_nslabs);
700 ent = debugfs_create_ulong("io_tlb_used", 0400,
701 d_swiotlb_usage, &io_tlb_used);
708 debugfs_remove_recursive(d_swiotlb_usage);
712 late_initcall(swiotlb_create_debugfs);