1 // SPDX-License-Identifier: GPL-2.0-only
3 * Dynamic DMA mapping support.
5 * This implementation is a fallback for platforms that do not support
6 * I/O TLBs (aka DMA address translation hardware).
7 * Copyright (C) 2000 Asit Mallick <Asit.K.Mallick@intel.com>
8 * Copyright (C) 2000 Goutham Rao <goutham.rao@intel.com>
9 * Copyright (C) 2000, 2003 Hewlett-Packard Co
10 * David Mosberger-Tang <davidm@hpl.hp.com>
12 * 03/05/07 davidm Switch from PCI-DMA to generic device DMA API.
13 * 00/12/13 davidm Rename to swiotlb.c and add mark_clean() to avoid
14 * unnecessary i-cache flushing.
15 * 04/07/.. ak Better overflow handling. Assorted fixes.
16 * 05/09/10 linville Add support for syncing ranges, support syncing for
17 * DMA_BIDIRECTIONAL mappings, miscellaneous cleanup.
18 * 08/12/11 beckyb Add highmem support
21 #define pr_fmt(fmt) "software IO TLB: " fmt
23 #include <linux/cache.h>
24 #include <linux/cc_platform.h>
25 #include <linux/ctype.h>
26 #include <linux/debugfs.h>
27 #include <linux/dma-direct.h>
28 #include <linux/dma-map-ops.h>
29 #include <linux/export.h>
30 #include <linux/gfp.h>
31 #include <linux/highmem.h>
33 #include <linux/iommu-helper.h>
34 #include <linux/init.h>
35 #include <linux/memblock.h>
37 #include <linux/pfn.h>
38 #include <linux/scatterlist.h>
39 #include <linux/set_memory.h>
40 #include <linux/spinlock.h>
41 #include <linux/string.h>
42 #include <linux/swiotlb.h>
43 #include <linux/types.h>
44 #ifdef CONFIG_DMA_RESTRICTED_POOL
46 #include <linux/of_fdt.h>
47 #include <linux/of_reserved_mem.h>
48 #include <linux/slab.h>
51 #define CREATE_TRACE_POINTS
52 #include <trace/events/swiotlb.h>
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 #define INVALID_PHYS_ADDR (~(phys_addr_t)0)
66 phys_addr_t orig_addr;
71 static bool swiotlb_force_bounce;
72 static bool swiotlb_force_disable;
74 struct io_tlb_mem io_tlb_default_mem;
76 phys_addr_t swiotlb_unencrypted_base;
78 static unsigned long default_nslabs = IO_TLB_DEFAULT_SIZE >> IO_TLB_SHIFT;
79 static unsigned long default_nareas;
82 * struct io_tlb_area - IO TLB memory area descriptor
84 * This is a single area with a single lock.
86 * @used: The number of used IO TLB block.
87 * @index: The slot index to start searching in this area for next round.
88 * @lock: The lock to protect the above data structures in the map and
98 * Round up number of slabs to the next power of 2. The last area is going
99 * be smaller than the rest if default_nslabs is not power of two.
100 * The number of slot in an area should be a multiple of IO_TLB_SEGSIZE,
101 * otherwise a segment may span two or more areas. It conflicts with free
102 * contiguous slots tracking: free slots are treated contiguous no matter
103 * whether they cross an area boundary.
105 * Return true if default_nslabs is rounded up.
107 static bool round_up_default_nslabs(void)
112 if (default_nslabs < IO_TLB_SEGSIZE * default_nareas)
113 default_nslabs = IO_TLB_SEGSIZE * default_nareas;
114 else if (is_power_of_2(default_nslabs))
116 default_nslabs = roundup_pow_of_two(default_nslabs);
120 static void swiotlb_adjust_nareas(unsigned int nareas)
122 /* use a single area when non is specified */
125 else if (!is_power_of_2(nareas))
126 nareas = roundup_pow_of_two(nareas);
128 default_nareas = nareas;
130 pr_info("area num %d.\n", nareas);
131 if (round_up_default_nslabs())
132 pr_info("SWIOTLB bounce buffer size roundup to %luMB",
133 (default_nslabs << IO_TLB_SHIFT) >> 20);
137 setup_io_tlb_npages(char *str)
140 /* avoid tail segment of size < IO_TLB_SEGSIZE */
142 ALIGN(simple_strtoul(str, &str, 0), IO_TLB_SEGSIZE);
147 swiotlb_adjust_nareas(simple_strtoul(str, &str, 0));
150 if (!strcmp(str, "force"))
151 swiotlb_force_bounce = true;
152 else if (!strcmp(str, "noforce"))
153 swiotlb_force_disable = true;
157 early_param("swiotlb", setup_io_tlb_npages);
159 unsigned int swiotlb_max_segment(void)
161 if (!io_tlb_default_mem.nslabs)
163 return rounddown(io_tlb_default_mem.nslabs << IO_TLB_SHIFT, PAGE_SIZE);
165 EXPORT_SYMBOL_GPL(swiotlb_max_segment);
167 unsigned long swiotlb_size_or_default(void)
169 return default_nslabs << IO_TLB_SHIFT;
172 void __init swiotlb_adjust_size(unsigned long size)
175 * If swiotlb parameter has not been specified, give a chance to
176 * architectures such as those supporting memory encryption to
177 * adjust/expand SWIOTLB size for their use.
179 if (default_nslabs != IO_TLB_DEFAULT_SIZE >> IO_TLB_SHIFT)
182 size = ALIGN(size, IO_TLB_SIZE);
183 default_nslabs = ALIGN(size >> IO_TLB_SHIFT, IO_TLB_SEGSIZE);
184 if (round_up_default_nslabs())
185 size = default_nslabs << IO_TLB_SHIFT;
186 pr_info("SWIOTLB bounce buffer size adjusted to %luMB", size >> 20);
189 void swiotlb_print_info(void)
191 struct io_tlb_mem *mem = &io_tlb_default_mem;
194 pr_warn("No low mem\n");
198 pr_info("mapped [mem %pa-%pa] (%luMB)\n", &mem->start, &mem->end,
199 (mem->nslabs << IO_TLB_SHIFT) >> 20);
202 static inline unsigned long io_tlb_offset(unsigned long val)
204 return val & (IO_TLB_SEGSIZE - 1);
207 static inline unsigned long nr_slots(u64 val)
209 return DIV_ROUND_UP(val, IO_TLB_SIZE);
213 * Remap swioltb memory in the unencrypted physical address space
214 * when swiotlb_unencrypted_base is set. (e.g. for Hyper-V AMD SEV-SNP
217 #ifdef CONFIG_HAS_IOMEM
218 static void *swiotlb_mem_remap(struct io_tlb_mem *mem, unsigned long bytes)
222 if (swiotlb_unencrypted_base) {
223 phys_addr_t paddr = mem->start + swiotlb_unencrypted_base;
225 vaddr = memremap(paddr, bytes, MEMREMAP_WB);
227 pr_err("Failed to map the unencrypted memory %pa size %lx.\n",
234 static void *swiotlb_mem_remap(struct io_tlb_mem *mem, unsigned long bytes)
241 * Early SWIOTLB allocation may be too early to allow an architecture to
242 * perform the desired operations. This function allows the architecture to
243 * call SWIOTLB when the operations are possible. It needs to be called
244 * before the SWIOTLB memory is used.
246 void __init swiotlb_update_mem_attributes(void)
248 struct io_tlb_mem *mem = &io_tlb_default_mem;
252 if (!mem->nslabs || mem->late_alloc)
254 vaddr = phys_to_virt(mem->start);
255 bytes = PAGE_ALIGN(mem->nslabs << IO_TLB_SHIFT);
256 set_memory_decrypted((unsigned long)vaddr, bytes >> PAGE_SHIFT);
258 mem->vaddr = swiotlb_mem_remap(mem, bytes);
263 static void swiotlb_init_io_tlb_mem(struct io_tlb_mem *mem, phys_addr_t start,
264 unsigned long nslabs, unsigned int flags,
265 bool late_alloc, unsigned int nareas)
267 void *vaddr = phys_to_virt(start);
268 unsigned long bytes = nslabs << IO_TLB_SHIFT, i;
270 mem->nslabs = nslabs;
272 mem->end = mem->start + bytes;
273 mem->late_alloc = late_alloc;
274 mem->nareas = nareas;
275 mem->area_nslabs = nslabs / mem->nareas;
277 mem->force_bounce = swiotlb_force_bounce || (flags & SWIOTLB_FORCE);
279 for (i = 0; i < mem->nareas; i++) {
280 spin_lock_init(&mem->areas[i].lock);
281 mem->areas[i].index = 0;
282 mem->areas[i].used = 0;
285 for (i = 0; i < mem->nslabs; i++) {
286 mem->slots[i].list = IO_TLB_SEGSIZE - io_tlb_offset(i);
287 mem->slots[i].orig_addr = INVALID_PHYS_ADDR;
288 mem->slots[i].alloc_size = 0;
292 * If swiotlb_unencrypted_base is set, the bounce buffer memory will
293 * be remapped and cleared in swiotlb_update_mem_attributes.
295 if (swiotlb_unencrypted_base)
298 memset(vaddr, 0, bytes);
304 * Statically reserve bounce buffer space and initialize bounce buffer data
305 * structures for the software IO TLB used to implement the DMA API.
307 void __init swiotlb_init_remap(bool addressing_limit, unsigned int flags,
308 int (*remap)(void *tlb, unsigned long nslabs))
310 struct io_tlb_mem *mem = &io_tlb_default_mem;
311 unsigned long nslabs;
316 if (!addressing_limit && !swiotlb_force_bounce)
318 if (swiotlb_force_disable)
322 * default_nslabs maybe changed when adjust area number.
323 * So allocate bounce buffer after adjusting area number.
326 swiotlb_adjust_nareas(num_possible_cpus());
328 nslabs = default_nslabs;
330 * By default allocate the bounce buffer memory from low memory, but
331 * allow to pick a location everywhere for hypervisors with guest
335 bytes = PAGE_ALIGN(nslabs << IO_TLB_SHIFT);
336 if (flags & SWIOTLB_ANY)
337 tlb = memblock_alloc(bytes, PAGE_SIZE);
339 tlb = memblock_alloc_low(bytes, PAGE_SIZE);
341 pr_warn("%s: failed to allocate tlb structure\n", __func__);
345 if (remap && remap(tlb, nslabs) < 0) {
346 memblock_free(tlb, PAGE_ALIGN(bytes));
348 nslabs = ALIGN(nslabs >> 1, IO_TLB_SEGSIZE);
349 if (nslabs >= IO_TLB_MIN_SLABS)
352 pr_warn("%s: Failed to remap %zu bytes\n", __func__, bytes);
356 alloc_size = PAGE_ALIGN(array_size(sizeof(*mem->slots), nslabs));
357 mem->slots = memblock_alloc(alloc_size, PAGE_SIZE);
359 pr_warn("%s: Failed to allocate %zu bytes align=0x%lx\n",
360 __func__, alloc_size, PAGE_SIZE);
364 mem->areas = memblock_alloc(array_size(sizeof(struct io_tlb_area),
365 default_nareas), SMP_CACHE_BYTES);
367 pr_warn("%s: Failed to allocate mem->areas.\n", __func__);
371 swiotlb_init_io_tlb_mem(mem, __pa(tlb), nslabs, flags, false,
374 if (flags & SWIOTLB_VERBOSE)
375 swiotlb_print_info();
378 void __init swiotlb_init(bool addressing_limit, unsigned int flags)
380 swiotlb_init_remap(addressing_limit, flags, NULL);
384 * Systems with larger DMA zones (those that don't support ISA) can
385 * initialize the swiotlb later using the slab allocator if needed.
386 * This should be just like above, but with some error catching.
388 int swiotlb_init_late(size_t size, gfp_t gfp_mask,
389 int (*remap)(void *tlb, unsigned long nslabs))
391 struct io_tlb_mem *mem = &io_tlb_default_mem;
392 unsigned long nslabs = ALIGN(size >> IO_TLB_SHIFT, IO_TLB_SEGSIZE);
393 unsigned char *vstart = NULL;
394 unsigned int order, area_order;
395 bool retried = false;
398 if (swiotlb_force_disable)
402 order = get_order(nslabs << IO_TLB_SHIFT);
403 nslabs = SLABS_PER_PAGE << order;
405 while ((SLABS_PER_PAGE << order) > IO_TLB_MIN_SLABS) {
406 vstart = (void *)__get_free_pages(gfp_mask | __GFP_NOWARN,
411 nslabs = SLABS_PER_PAGE << order;
419 rc = remap(vstart, nslabs);
421 free_pages((unsigned long)vstart, order);
423 nslabs = ALIGN(nslabs >> 1, IO_TLB_SEGSIZE);
424 if (nslabs < IO_TLB_MIN_SLABS)
431 pr_warn("only able to allocate %ld MB\n",
432 (PAGE_SIZE << order) >> 20);
436 swiotlb_adjust_nareas(num_possible_cpus());
438 area_order = get_order(array_size(sizeof(*mem->areas),
440 mem->areas = (struct io_tlb_area *)
441 __get_free_pages(GFP_KERNEL | __GFP_ZERO, area_order);
445 mem->slots = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
446 get_order(array_size(sizeof(*mem->slots), nslabs)));
450 set_memory_decrypted((unsigned long)vstart,
451 (nslabs << IO_TLB_SHIFT) >> PAGE_SHIFT);
452 swiotlb_init_io_tlb_mem(mem, virt_to_phys(vstart), nslabs, 0, true,
455 swiotlb_print_info();
459 free_pages((unsigned long)mem->areas, area_order);
461 free_pages((unsigned long)vstart, order);
465 void __init swiotlb_exit(void)
467 struct io_tlb_mem *mem = &io_tlb_default_mem;
468 unsigned long tbl_vaddr;
469 size_t tbl_size, slots_size;
470 unsigned int area_order;
472 if (swiotlb_force_bounce)
478 pr_info("tearing down default memory pool\n");
479 tbl_vaddr = (unsigned long)phys_to_virt(mem->start);
480 tbl_size = PAGE_ALIGN(mem->end - mem->start);
481 slots_size = PAGE_ALIGN(array_size(sizeof(*mem->slots), mem->nslabs));
483 set_memory_encrypted(tbl_vaddr, tbl_size >> PAGE_SHIFT);
484 if (mem->late_alloc) {
485 area_order = get_order(array_size(sizeof(*mem->areas),
487 free_pages((unsigned long)mem->areas, area_order);
488 free_pages(tbl_vaddr, get_order(tbl_size));
489 free_pages((unsigned long)mem->slots, get_order(slots_size));
491 memblock_free_late(__pa(mem->areas),
492 array_size(sizeof(*mem->areas), mem->nareas));
493 memblock_free_late(mem->start, tbl_size);
494 memblock_free_late(__pa(mem->slots), slots_size);
497 memset(mem, 0, sizeof(*mem));
501 * Return the offset into a iotlb slot required to keep the device happy.
503 static unsigned int swiotlb_align_offset(struct device *dev, u64 addr)
505 return addr & dma_get_min_align_mask(dev) & (IO_TLB_SIZE - 1);
509 * Bounce: copy the swiotlb buffer from or back to the original dma location
511 static void swiotlb_bounce(struct device *dev, phys_addr_t tlb_addr, size_t size,
512 enum dma_data_direction dir)
514 struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
515 int index = (tlb_addr - mem->start) >> IO_TLB_SHIFT;
516 phys_addr_t orig_addr = mem->slots[index].orig_addr;
517 size_t alloc_size = mem->slots[index].alloc_size;
518 unsigned long pfn = PFN_DOWN(orig_addr);
519 unsigned char *vaddr = mem->vaddr + tlb_addr - mem->start;
520 unsigned int tlb_offset, orig_addr_offset;
522 if (orig_addr == INVALID_PHYS_ADDR)
525 tlb_offset = tlb_addr & (IO_TLB_SIZE - 1);
526 orig_addr_offset = swiotlb_align_offset(dev, orig_addr);
527 if (tlb_offset < orig_addr_offset) {
528 dev_WARN_ONCE(dev, 1,
529 "Access before mapping start detected. orig offset %u, requested offset %u.\n",
530 orig_addr_offset, tlb_offset);
534 tlb_offset -= orig_addr_offset;
535 if (tlb_offset > alloc_size) {
536 dev_WARN_ONCE(dev, 1,
537 "Buffer overflow detected. Allocation size: %zu. Mapping size: %zu+%u.\n",
538 alloc_size, size, tlb_offset);
542 orig_addr += tlb_offset;
543 alloc_size -= tlb_offset;
545 if (size > alloc_size) {
546 dev_WARN_ONCE(dev, 1,
547 "Buffer overflow detected. Allocation size: %zu. Mapping size: %zu.\n",
552 if (PageHighMem(pfn_to_page(pfn))) {
553 unsigned int offset = orig_addr & ~PAGE_MASK;
559 sz = min_t(size_t, PAGE_SIZE - offset, size);
561 local_irq_save(flags);
562 page = pfn_to_page(pfn);
563 if (dir == DMA_TO_DEVICE)
564 memcpy_from_page(vaddr, page, offset, sz);
566 memcpy_to_page(page, offset, vaddr, sz);
567 local_irq_restore(flags);
574 } else if (dir == DMA_TO_DEVICE) {
575 memcpy(vaddr, phys_to_virt(orig_addr), size);
577 memcpy(phys_to_virt(orig_addr), vaddr, size);
581 static inline phys_addr_t slot_addr(phys_addr_t start, phys_addr_t idx)
583 return start + (idx << IO_TLB_SHIFT);
587 * Carefully handle integer overflow which can occur when boundary_mask == ~0UL.
589 static inline unsigned long get_max_slots(unsigned long boundary_mask)
591 if (boundary_mask == ~0UL)
592 return 1UL << (BITS_PER_LONG - IO_TLB_SHIFT);
593 return nr_slots(boundary_mask + 1);
596 static unsigned int wrap_area_index(struct io_tlb_mem *mem, unsigned int index)
598 if (index >= mem->area_nslabs)
604 * Find a suitable number of IO TLB entries size that will fit this request and
605 * allocate a buffer from that IO TLB pool.
607 static int swiotlb_do_find_slots(struct device *dev, int area_index,
608 phys_addr_t orig_addr, size_t alloc_size,
609 unsigned int alloc_align_mask)
611 struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
612 struct io_tlb_area *area = mem->areas + area_index;
613 unsigned long boundary_mask = dma_get_seg_boundary(dev);
614 dma_addr_t tbl_dma_addr =
615 phys_to_dma_unencrypted(dev, mem->start) & boundary_mask;
616 unsigned long max_slots = get_max_slots(boundary_mask);
617 unsigned int iotlb_align_mask =
618 dma_get_min_align_mask(dev) & ~(IO_TLB_SIZE - 1);
619 unsigned int nslots = nr_slots(alloc_size), stride;
620 unsigned int index, wrap, count = 0, i;
621 unsigned int offset = swiotlb_align_offset(dev, orig_addr);
623 unsigned int slot_base;
624 unsigned int slot_index;
627 BUG_ON(area_index >= mem->nareas);
630 * For mappings with an alignment requirement don't bother looping to
631 * unaligned slots once we found an aligned one. For allocations of
632 * PAGE_SIZE or larger only look for page aligned allocations.
634 stride = (iotlb_align_mask >> IO_TLB_SHIFT) + 1;
635 if (alloc_size >= PAGE_SIZE)
636 stride = max(stride, stride << (PAGE_SHIFT - IO_TLB_SHIFT));
637 stride = max(stride, (alloc_align_mask >> IO_TLB_SHIFT) + 1);
639 spin_lock_irqsave(&area->lock, flags);
640 if (unlikely(nslots > mem->area_nslabs - area->used))
643 slot_base = area_index * mem->area_nslabs;
644 index = wrap = wrap_area_index(mem, ALIGN(area->index, stride));
647 slot_index = slot_base + index;
650 (slot_addr(tbl_dma_addr, slot_index) &
651 iotlb_align_mask) != (orig_addr & iotlb_align_mask)) {
652 index = wrap_area_index(mem, index + 1);
657 * If we find a slot that indicates we have 'nslots' number of
658 * contiguous buffers, we allocate the buffers from that slot
659 * and mark the entries as '0' indicating unavailable.
661 if (!iommu_is_span_boundary(slot_index, nslots,
662 nr_slots(tbl_dma_addr),
664 if (mem->slots[slot_index].list >= nslots)
667 index = wrap_area_index(mem, index + stride);
668 } while (index != wrap);
671 spin_unlock_irqrestore(&area->lock, flags);
675 for (i = slot_index; i < slot_index + nslots; i++) {
676 mem->slots[i].list = 0;
677 mem->slots[i].alloc_size = alloc_size - (offset +
678 ((i - slot_index) << IO_TLB_SHIFT));
680 for (i = slot_index - 1;
681 io_tlb_offset(i) != IO_TLB_SEGSIZE - 1 &&
682 mem->slots[i].list; i--)
683 mem->slots[i].list = ++count;
686 * Update the indices to avoid searching in the next round.
688 if (index + nslots < mem->area_nslabs)
689 area->index = index + nslots;
692 area->used += nslots;
693 spin_unlock_irqrestore(&area->lock, flags);
697 static int swiotlb_find_slots(struct device *dev, phys_addr_t orig_addr,
698 size_t alloc_size, unsigned int alloc_align_mask)
700 struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
701 int start = raw_smp_processor_id() & (mem->nareas - 1);
702 int i = start, index;
705 index = swiotlb_do_find_slots(dev, i, orig_addr, alloc_size,
709 if (++i >= mem->nareas)
711 } while (i != start);
716 static unsigned long mem_used(struct io_tlb_mem *mem)
719 unsigned long used = 0;
721 for (i = 0; i < mem->nareas; i++)
722 used += mem->areas[i].used;
726 phys_addr_t swiotlb_tbl_map_single(struct device *dev, phys_addr_t orig_addr,
727 size_t mapping_size, size_t alloc_size,
728 unsigned int alloc_align_mask, enum dma_data_direction dir,
731 struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
732 unsigned int offset = swiotlb_align_offset(dev, orig_addr);
735 phys_addr_t tlb_addr;
737 if (!mem || !mem->nslabs) {
738 dev_warn_ratelimited(dev,
739 "Can not allocate SWIOTLB buffer earlier and can't now provide you with the DMA bounce buffer");
740 return (phys_addr_t)DMA_MAPPING_ERROR;
743 if (cc_platform_has(CC_ATTR_MEM_ENCRYPT))
744 pr_warn_once("Memory encryption is active and system is using DMA bounce buffers\n");
746 if (mapping_size > alloc_size) {
747 dev_warn_once(dev, "Invalid sizes (mapping: %zd bytes, alloc: %zd bytes)",
748 mapping_size, alloc_size);
749 return (phys_addr_t)DMA_MAPPING_ERROR;
752 index = swiotlb_find_slots(dev, orig_addr,
753 alloc_size + offset, alloc_align_mask);
755 if (!(attrs & DMA_ATTR_NO_WARN))
756 dev_warn_ratelimited(dev,
757 "swiotlb buffer is full (sz: %zd bytes), total %lu (slots), used %lu (slots)\n",
758 alloc_size, mem->nslabs, mem_used(mem));
759 return (phys_addr_t)DMA_MAPPING_ERROR;
763 * Save away the mapping from the original address to the DMA address.
764 * This is needed when we sync the memory. Then we sync the buffer if
767 for (i = 0; i < nr_slots(alloc_size + offset); i++)
768 mem->slots[index + i].orig_addr = slot_addr(orig_addr, i);
769 tlb_addr = slot_addr(mem->start, index) + offset;
771 * When dir == DMA_FROM_DEVICE we could omit the copy from the orig
772 * to the tlb buffer, if we knew for sure the device will
773 * overwrite the entire current content. But we don't. Thus
774 * unconditional bounce may prevent leaking swiotlb content (i.e.
775 * kernel memory) to user-space.
777 swiotlb_bounce(dev, tlb_addr, mapping_size, DMA_TO_DEVICE);
781 static void swiotlb_release_slots(struct device *dev, phys_addr_t tlb_addr)
783 struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
785 unsigned int offset = swiotlb_align_offset(dev, tlb_addr);
786 int index = (tlb_addr - offset - mem->start) >> IO_TLB_SHIFT;
787 int nslots = nr_slots(mem->slots[index].alloc_size + offset);
788 int aindex = index / mem->area_nslabs;
789 struct io_tlb_area *area = &mem->areas[aindex];
793 * Return the buffer to the free list by setting the corresponding
794 * entries to indicate the number of contiguous entries available.
795 * While returning the entries to the free list, we merge the entries
796 * with slots below and above the pool being returned.
798 BUG_ON(aindex >= mem->nareas);
800 spin_lock_irqsave(&area->lock, flags);
801 if (index + nslots < ALIGN(index + 1, IO_TLB_SEGSIZE))
802 count = mem->slots[index + nslots].list;
807 * Step 1: return the slots to the free list, merging the slots with
810 for (i = index + nslots - 1; i >= index; i--) {
811 mem->slots[i].list = ++count;
812 mem->slots[i].orig_addr = INVALID_PHYS_ADDR;
813 mem->slots[i].alloc_size = 0;
817 * Step 2: merge the returned slots with the preceding slots, if
818 * available (non zero)
821 io_tlb_offset(i) != IO_TLB_SEGSIZE - 1 && mem->slots[i].list;
823 mem->slots[i].list = ++count;
824 area->used -= nslots;
825 spin_unlock_irqrestore(&area->lock, flags);
829 * tlb_addr is the physical address of the bounce buffer to unmap.
831 void swiotlb_tbl_unmap_single(struct device *dev, phys_addr_t tlb_addr,
832 size_t mapping_size, enum dma_data_direction dir,
836 * First, sync the memory before unmapping the entry
838 if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
839 (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL))
840 swiotlb_bounce(dev, tlb_addr, mapping_size, DMA_FROM_DEVICE);
842 swiotlb_release_slots(dev, tlb_addr);
845 void swiotlb_sync_single_for_device(struct device *dev, phys_addr_t tlb_addr,
846 size_t size, enum dma_data_direction dir)
848 if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL)
849 swiotlb_bounce(dev, tlb_addr, size, DMA_TO_DEVICE);
851 BUG_ON(dir != DMA_FROM_DEVICE);
854 void swiotlb_sync_single_for_cpu(struct device *dev, phys_addr_t tlb_addr,
855 size_t size, enum dma_data_direction dir)
857 if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
858 swiotlb_bounce(dev, tlb_addr, size, DMA_FROM_DEVICE);
860 BUG_ON(dir != DMA_TO_DEVICE);
864 * Create a swiotlb mapping for the buffer at @paddr, and in case of DMAing
865 * to the device copy the data into it as well.
867 dma_addr_t swiotlb_map(struct device *dev, phys_addr_t paddr, size_t size,
868 enum dma_data_direction dir, unsigned long attrs)
870 phys_addr_t swiotlb_addr;
873 trace_swiotlb_bounced(dev, phys_to_dma(dev, paddr), size);
875 swiotlb_addr = swiotlb_tbl_map_single(dev, paddr, size, size, 0, dir,
877 if (swiotlb_addr == (phys_addr_t)DMA_MAPPING_ERROR)
878 return DMA_MAPPING_ERROR;
880 /* Ensure that the address returned is DMA'ble */
881 dma_addr = phys_to_dma_unencrypted(dev, swiotlb_addr);
882 if (unlikely(!dma_capable(dev, dma_addr, size, true))) {
883 swiotlb_tbl_unmap_single(dev, swiotlb_addr, size, dir,
884 attrs | DMA_ATTR_SKIP_CPU_SYNC);
885 dev_WARN_ONCE(dev, 1,
886 "swiotlb addr %pad+%zu overflow (mask %llx, bus limit %llx).\n",
887 &dma_addr, size, *dev->dma_mask, dev->bus_dma_limit);
888 return DMA_MAPPING_ERROR;
891 if (!dev_is_dma_coherent(dev) && !(attrs & DMA_ATTR_SKIP_CPU_SYNC))
892 arch_sync_dma_for_device(swiotlb_addr, size, dir);
896 size_t swiotlb_max_mapping_size(struct device *dev)
898 int min_align_mask = dma_get_min_align_mask(dev);
902 * swiotlb_find_slots() skips slots according to
903 * min align mask. This affects max mapping size.
904 * Take it into acount here.
907 min_align = roundup(min_align_mask, IO_TLB_SIZE);
909 return ((size_t)IO_TLB_SIZE) * IO_TLB_SEGSIZE - min_align;
912 bool is_swiotlb_active(struct device *dev)
914 struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
916 return mem && mem->nslabs;
918 EXPORT_SYMBOL_GPL(is_swiotlb_active);
920 static int io_tlb_used_get(void *data, u64 *val)
922 struct io_tlb_mem *mem = data;
924 *val = mem_used(mem);
927 DEFINE_DEBUGFS_ATTRIBUTE(fops_io_tlb_used, io_tlb_used_get, NULL, "%llu\n");
929 static void swiotlb_create_debugfs_files(struct io_tlb_mem *mem,
932 mem->debugfs = debugfs_create_dir(dirname, io_tlb_default_mem.debugfs);
936 debugfs_create_ulong("io_tlb_nslabs", 0400, mem->debugfs, &mem->nslabs);
937 debugfs_create_file("io_tlb_used", 0400, mem->debugfs, mem,
941 static int __init __maybe_unused swiotlb_create_default_debugfs(void)
943 swiotlb_create_debugfs_files(&io_tlb_default_mem, "swiotlb");
947 #ifdef CONFIG_DEBUG_FS
948 late_initcall(swiotlb_create_default_debugfs);
951 #ifdef CONFIG_DMA_RESTRICTED_POOL
953 struct page *swiotlb_alloc(struct device *dev, size_t size)
955 struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
956 phys_addr_t tlb_addr;
962 index = swiotlb_find_slots(dev, 0, size, 0);
966 tlb_addr = slot_addr(mem->start, index);
968 return pfn_to_page(PFN_DOWN(tlb_addr));
971 bool swiotlb_free(struct device *dev, struct page *page, size_t size)
973 phys_addr_t tlb_addr = page_to_phys(page);
975 if (!is_swiotlb_buffer(dev, tlb_addr))
978 swiotlb_release_slots(dev, tlb_addr);
983 static int rmem_swiotlb_device_init(struct reserved_mem *rmem,
986 struct io_tlb_mem *mem = rmem->priv;
987 unsigned long nslabs = rmem->size >> IO_TLB_SHIFT;
989 /* Set Per-device io tlb area to one */
990 unsigned int nareas = 1;
992 if (PageHighMem(pfn_to_page(PHYS_PFN(rmem->base)))) {
993 dev_err(dev, "Restricted DMA pool must be accessible within the linear mapping.");
998 * Since multiple devices can share the same pool, the private data,
999 * io_tlb_mem struct, will be initialized by the first device attached
1003 mem = kzalloc(sizeof(*mem), GFP_KERNEL);
1007 mem->slots = kcalloc(nslabs, sizeof(*mem->slots), GFP_KERNEL);
1013 mem->areas = kcalloc(nareas, sizeof(*mem->areas),
1021 set_memory_decrypted((unsigned long)phys_to_virt(rmem->base),
1022 rmem->size >> PAGE_SHIFT);
1023 swiotlb_init_io_tlb_mem(mem, rmem->base, nslabs, SWIOTLB_FORCE,
1025 mem->for_alloc = true;
1029 swiotlb_create_debugfs_files(mem, rmem->name);
1032 dev->dma_io_tlb_mem = mem;
1037 static void rmem_swiotlb_device_release(struct reserved_mem *rmem,
1040 dev->dma_io_tlb_mem = &io_tlb_default_mem;
1043 static const struct reserved_mem_ops rmem_swiotlb_ops = {
1044 .device_init = rmem_swiotlb_device_init,
1045 .device_release = rmem_swiotlb_device_release,
1048 static int __init rmem_swiotlb_setup(struct reserved_mem *rmem)
1050 unsigned long node = rmem->fdt_node;
1052 if (of_get_flat_dt_prop(node, "reusable", NULL) ||
1053 of_get_flat_dt_prop(node, "linux,cma-default", NULL) ||
1054 of_get_flat_dt_prop(node, "linux,dma-default", NULL) ||
1055 of_get_flat_dt_prop(node, "no-map", NULL))
1058 rmem->ops = &rmem_swiotlb_ops;
1059 pr_info("Reserved memory: created restricted DMA pool at %pa, size %ld MiB\n",
1060 &rmem->base, (unsigned long)rmem->size / SZ_1M);
1064 RESERVEDMEM_OF_DECLARE(dma, "restricted-dma-pool", rmem_swiotlb_setup);
1065 #endif /* CONFIG_DMA_RESTRICTED_POOL */