xref: /openbmc/linux/kernel/dma/swiotlb.c (revision 5fe1d61a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Dynamic DMA mapping support.
4  *
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>
11  *
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
19  */
20 
21 #define pr_fmt(fmt) "software IO TLB: " fmt
22 
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>
32 #include <linux/io.h>
33 #include <linux/iommu-helper.h>
34 #include <linux/init.h>
35 #include <linux/memblock.h>
36 #include <linux/mm.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
45 #include <linux/of.h>
46 #include <linux/of_fdt.h>
47 #include <linux/of_reserved_mem.h>
48 #include <linux/slab.h>
49 #endif
50 
51 #define CREATE_TRACE_POINTS
52 #include <trace/events/swiotlb.h>
53 
54 #define SLABS_PER_PAGE (1 << (PAGE_SHIFT - IO_TLB_SHIFT))
55 
56 /*
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.
60  */
61 #define IO_TLB_MIN_SLABS ((1<<20) >> IO_TLB_SHIFT)
62 
63 #define INVALID_PHYS_ADDR (~(phys_addr_t)0)
64 
65 static bool swiotlb_force_bounce;
66 static bool swiotlb_force_disable;
67 
68 struct io_tlb_mem io_tlb_default_mem;
69 
70 phys_addr_t swiotlb_unencrypted_base;
71 
72 static unsigned long default_nslabs = IO_TLB_DEFAULT_SIZE >> IO_TLB_SHIFT;
73 
74 static int __init
75 setup_io_tlb_npages(char *str)
76 {
77 	if (isdigit(*str)) {
78 		/* avoid tail segment of size < IO_TLB_SEGSIZE */
79 		default_nslabs =
80 			ALIGN(simple_strtoul(str, &str, 0), IO_TLB_SEGSIZE);
81 	}
82 	if (*str == ',')
83 		++str;
84 	if (!strcmp(str, "force"))
85 		swiotlb_force_bounce = true;
86 	else if (!strcmp(str, "noforce"))
87 		swiotlb_force_disable = true;
88 
89 	return 0;
90 }
91 early_param("swiotlb", setup_io_tlb_npages);
92 
93 unsigned int swiotlb_max_segment(void)
94 {
95 	if (!io_tlb_default_mem.nslabs)
96 		return 0;
97 	return rounddown(io_tlb_default_mem.nslabs << IO_TLB_SHIFT, PAGE_SIZE);
98 }
99 EXPORT_SYMBOL_GPL(swiotlb_max_segment);
100 
101 unsigned long swiotlb_size_or_default(void)
102 {
103 	return default_nslabs << IO_TLB_SHIFT;
104 }
105 
106 void __init swiotlb_adjust_size(unsigned long size)
107 {
108 	/*
109 	 * If swiotlb parameter has not been specified, give a chance to
110 	 * architectures such as those supporting memory encryption to
111 	 * adjust/expand SWIOTLB size for their use.
112 	 */
113 	if (default_nslabs != IO_TLB_DEFAULT_SIZE >> IO_TLB_SHIFT)
114 		return;
115 	size = ALIGN(size, IO_TLB_SIZE);
116 	default_nslabs = ALIGN(size >> IO_TLB_SHIFT, IO_TLB_SEGSIZE);
117 	pr_info("SWIOTLB bounce buffer size adjusted to %luMB", size >> 20);
118 }
119 
120 void swiotlb_print_info(void)
121 {
122 	struct io_tlb_mem *mem = &io_tlb_default_mem;
123 
124 	if (!mem->nslabs) {
125 		pr_warn("No low mem\n");
126 		return;
127 	}
128 
129 	pr_info("mapped [mem %pa-%pa] (%luMB)\n", &mem->start, &mem->end,
130 	       (mem->nslabs << IO_TLB_SHIFT) >> 20);
131 }
132 
133 static inline unsigned long io_tlb_offset(unsigned long val)
134 {
135 	return val & (IO_TLB_SEGSIZE - 1);
136 }
137 
138 static inline unsigned long nr_slots(u64 val)
139 {
140 	return DIV_ROUND_UP(val, IO_TLB_SIZE);
141 }
142 
143 /*
144  * Remap swioltb memory in the unencrypted physical address space
145  * when swiotlb_unencrypted_base is set. (e.g. for Hyper-V AMD SEV-SNP
146  * Isolation VMs).
147  */
148 #ifdef CONFIG_HAS_IOMEM
149 static void *swiotlb_mem_remap(struct io_tlb_mem *mem, unsigned long bytes)
150 {
151 	void *vaddr = NULL;
152 
153 	if (swiotlb_unencrypted_base) {
154 		phys_addr_t paddr = mem->start + swiotlb_unencrypted_base;
155 
156 		vaddr = memremap(paddr, bytes, MEMREMAP_WB);
157 		if (!vaddr)
158 			pr_err("Failed to map the unencrypted memory %pa size %lx.\n",
159 			       &paddr, bytes);
160 	}
161 
162 	return vaddr;
163 }
164 #else
165 static void *swiotlb_mem_remap(struct io_tlb_mem *mem, unsigned long bytes)
166 {
167 	return NULL;
168 }
169 #endif
170 
171 /*
172  * Early SWIOTLB allocation may be too early to allow an architecture to
173  * perform the desired operations.  This function allows the architecture to
174  * call SWIOTLB when the operations are possible.  It needs to be called
175  * before the SWIOTLB memory is used.
176  */
177 void __init swiotlb_update_mem_attributes(void)
178 {
179 	struct io_tlb_mem *mem = &io_tlb_default_mem;
180 	void *vaddr;
181 	unsigned long bytes;
182 
183 	if (!mem->nslabs || mem->late_alloc)
184 		return;
185 	vaddr = phys_to_virt(mem->start);
186 	bytes = PAGE_ALIGN(mem->nslabs << IO_TLB_SHIFT);
187 	set_memory_decrypted((unsigned long)vaddr, bytes >> PAGE_SHIFT);
188 
189 	mem->vaddr = swiotlb_mem_remap(mem, bytes);
190 	if (!mem->vaddr)
191 		mem->vaddr = vaddr;
192 }
193 
194 static void swiotlb_init_io_tlb_mem(struct io_tlb_mem *mem, phys_addr_t start,
195 		unsigned long nslabs, unsigned int flags, bool late_alloc)
196 {
197 	void *vaddr = phys_to_virt(start);
198 	unsigned long bytes = nslabs << IO_TLB_SHIFT, i;
199 
200 	mem->nslabs = nslabs;
201 	mem->start = start;
202 	mem->end = mem->start + bytes;
203 	mem->index = 0;
204 	mem->late_alloc = late_alloc;
205 
206 	mem->force_bounce = swiotlb_force_bounce || (flags & SWIOTLB_FORCE);
207 
208 	spin_lock_init(&mem->lock);
209 	for (i = 0; i < mem->nslabs; i++) {
210 		mem->slots[i].list = IO_TLB_SEGSIZE - io_tlb_offset(i);
211 		mem->slots[i].orig_addr = INVALID_PHYS_ADDR;
212 		mem->slots[i].alloc_size = 0;
213 	}
214 
215 	/*
216 	 * If swiotlb_unencrypted_base is set, the bounce buffer memory will
217 	 * be remapped and cleared in swiotlb_update_mem_attributes.
218 	 */
219 	if (swiotlb_unencrypted_base)
220 		return;
221 
222 	memset(vaddr, 0, bytes);
223 	mem->vaddr = vaddr;
224 	return;
225 }
226 
227 /*
228  * Statically reserve bounce buffer space and initialize bounce buffer data
229  * structures for the software IO TLB used to implement the DMA API.
230  */
231 void __init swiotlb_init_remap(bool addressing_limit, unsigned int flags,
232 		int (*remap)(void *tlb, unsigned long nslabs))
233 {
234 	struct io_tlb_mem *mem = &io_tlb_default_mem;
235 	unsigned long nslabs = default_nslabs;
236 	size_t alloc_size;
237 	size_t bytes;
238 	void *tlb;
239 
240 	if (!addressing_limit && !swiotlb_force_bounce)
241 		return;
242 	if (swiotlb_force_disable)
243 		return;
244 
245 	/*
246 	 * By default allocate the bounce buffer memory from low memory, but
247 	 * allow to pick a location everywhere for hypervisors with guest
248 	 * memory encryption.
249 	 */
250 retry:
251 	bytes = PAGE_ALIGN(nslabs << IO_TLB_SHIFT);
252 	if (flags & SWIOTLB_ANY)
253 		tlb = memblock_alloc(bytes, PAGE_SIZE);
254 	else
255 		tlb = memblock_alloc_low(bytes, PAGE_SIZE);
256 	if (!tlb) {
257 		pr_warn("%s: failed to allocate tlb structure\n", __func__);
258 		return;
259 	}
260 
261 	if (remap && remap(tlb, nslabs) < 0) {
262 		memblock_free(tlb, PAGE_ALIGN(bytes));
263 
264 		nslabs = ALIGN(nslabs >> 1, IO_TLB_SEGSIZE);
265 		if (nslabs < IO_TLB_MIN_SLABS)
266 			panic("%s: Failed to remap %zu bytes\n",
267 			      __func__, bytes);
268 		goto retry;
269 	}
270 
271 	alloc_size = PAGE_ALIGN(array_size(sizeof(*mem->slots), nslabs));
272 	mem->slots = memblock_alloc(alloc_size, PAGE_SIZE);
273 	if (!mem->slots)
274 		panic("%s: Failed to allocate %zu bytes align=0x%lx\n",
275 		      __func__, alloc_size, PAGE_SIZE);
276 
277 	swiotlb_init_io_tlb_mem(mem, __pa(tlb), nslabs, flags, false);
278 
279 	if (flags & SWIOTLB_VERBOSE)
280 		swiotlb_print_info();
281 }
282 
283 void __init swiotlb_init(bool addressing_limit, unsigned int flags)
284 {
285 	return swiotlb_init_remap(addressing_limit, flags, NULL);
286 }
287 
288 /*
289  * Systems with larger DMA zones (those that don't support ISA) can
290  * initialize the swiotlb later using the slab allocator if needed.
291  * This should be just like above, but with some error catching.
292  */
293 int swiotlb_init_late(size_t size, gfp_t gfp_mask,
294 		int (*remap)(void *tlb, unsigned long nslabs))
295 {
296 	struct io_tlb_mem *mem = &io_tlb_default_mem;
297 	unsigned long nslabs = ALIGN(size >> IO_TLB_SHIFT, IO_TLB_SEGSIZE);
298 	unsigned char *vstart = NULL;
299 	unsigned int order;
300 	bool retried = false;
301 	int rc = 0;
302 
303 	if (swiotlb_force_disable)
304 		return 0;
305 
306 retry:
307 	order = get_order(nslabs << IO_TLB_SHIFT);
308 	nslabs = SLABS_PER_PAGE << order;
309 
310 	while ((SLABS_PER_PAGE << order) > IO_TLB_MIN_SLABS) {
311 		vstart = (void *)__get_free_pages(gfp_mask | __GFP_NOWARN,
312 						  order);
313 		if (vstart)
314 			break;
315 		order--;
316 		nslabs = SLABS_PER_PAGE << order;
317 		retried = true;
318 	}
319 
320 	if (!vstart)
321 		return -ENOMEM;
322 
323 	if (remap)
324 		rc = remap(vstart, nslabs);
325 	if (rc) {
326 		free_pages((unsigned long)vstart, order);
327 
328 		nslabs = ALIGN(nslabs >> 1, IO_TLB_SEGSIZE);
329 		if (nslabs < IO_TLB_MIN_SLABS)
330 			return rc;
331 		retried = true;
332 		goto retry;
333 	}
334 
335 	if (retried) {
336 		pr_warn("only able to allocate %ld MB\n",
337 			(PAGE_SIZE << order) >> 20);
338 	}
339 
340 	mem->slots = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
341 		get_order(array_size(sizeof(*mem->slots), nslabs)));
342 	if (!mem->slots) {
343 		free_pages((unsigned long)vstart, order);
344 		return -ENOMEM;
345 	}
346 
347 	set_memory_decrypted((unsigned long)vstart,
348 			     (nslabs << IO_TLB_SHIFT) >> PAGE_SHIFT);
349 	swiotlb_init_io_tlb_mem(mem, virt_to_phys(vstart), nslabs, 0, true);
350 
351 	swiotlb_print_info();
352 	return 0;
353 }
354 
355 void __init swiotlb_exit(void)
356 {
357 	struct io_tlb_mem *mem = &io_tlb_default_mem;
358 	unsigned long tbl_vaddr;
359 	size_t tbl_size, slots_size;
360 
361 	if (swiotlb_force_bounce)
362 		return;
363 
364 	if (!mem->nslabs)
365 		return;
366 
367 	pr_info("tearing down default memory pool\n");
368 	tbl_vaddr = (unsigned long)phys_to_virt(mem->start);
369 	tbl_size = PAGE_ALIGN(mem->end - mem->start);
370 	slots_size = PAGE_ALIGN(array_size(sizeof(*mem->slots), mem->nslabs));
371 
372 	set_memory_encrypted(tbl_vaddr, tbl_size >> PAGE_SHIFT);
373 	if (mem->late_alloc) {
374 		free_pages(tbl_vaddr, get_order(tbl_size));
375 		free_pages((unsigned long)mem->slots, get_order(slots_size));
376 	} else {
377 		memblock_free_late(mem->start, tbl_size);
378 		memblock_free_late(__pa(mem->slots), slots_size);
379 	}
380 
381 	memset(mem, 0, sizeof(*mem));
382 }
383 
384 /*
385  * Return the offset into a iotlb slot required to keep the device happy.
386  */
387 static unsigned int swiotlb_align_offset(struct device *dev, u64 addr)
388 {
389 	return addr & dma_get_min_align_mask(dev) & (IO_TLB_SIZE - 1);
390 }
391 
392 /*
393  * Bounce: copy the swiotlb buffer from or back to the original dma location
394  */
395 static void swiotlb_bounce(struct device *dev, phys_addr_t tlb_addr, size_t size,
396 			   enum dma_data_direction dir)
397 {
398 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
399 	int index = (tlb_addr - mem->start) >> IO_TLB_SHIFT;
400 	phys_addr_t orig_addr = mem->slots[index].orig_addr;
401 	size_t alloc_size = mem->slots[index].alloc_size;
402 	unsigned long pfn = PFN_DOWN(orig_addr);
403 	unsigned char *vaddr = mem->vaddr + tlb_addr - mem->start;
404 	unsigned int tlb_offset, orig_addr_offset;
405 
406 	if (orig_addr == INVALID_PHYS_ADDR)
407 		return;
408 
409 	tlb_offset = tlb_addr & (IO_TLB_SIZE - 1);
410 	orig_addr_offset = swiotlb_align_offset(dev, orig_addr);
411 	if (tlb_offset < orig_addr_offset) {
412 		dev_WARN_ONCE(dev, 1,
413 			"Access before mapping start detected. orig offset %u, requested offset %u.\n",
414 			orig_addr_offset, tlb_offset);
415 		return;
416 	}
417 
418 	tlb_offset -= orig_addr_offset;
419 	if (tlb_offset > alloc_size) {
420 		dev_WARN_ONCE(dev, 1,
421 			"Buffer overflow detected. Allocation size: %zu. Mapping size: %zu+%u.\n",
422 			alloc_size, size, tlb_offset);
423 		return;
424 	}
425 
426 	orig_addr += tlb_offset;
427 	alloc_size -= tlb_offset;
428 
429 	if (size > alloc_size) {
430 		dev_WARN_ONCE(dev, 1,
431 			"Buffer overflow detected. Allocation size: %zu. Mapping size: %zu.\n",
432 			alloc_size, size);
433 		size = alloc_size;
434 	}
435 
436 	if (PageHighMem(pfn_to_page(pfn))) {
437 		/* The buffer does not have a mapping.  Map it in and copy */
438 		unsigned int offset = orig_addr & ~PAGE_MASK;
439 		char *buffer;
440 		unsigned int sz = 0;
441 		unsigned long flags;
442 
443 		while (size) {
444 			sz = min_t(size_t, PAGE_SIZE - offset, size);
445 
446 			local_irq_save(flags);
447 			buffer = kmap_atomic(pfn_to_page(pfn));
448 			if (dir == DMA_TO_DEVICE)
449 				memcpy(vaddr, buffer + offset, sz);
450 			else
451 				memcpy(buffer + offset, vaddr, sz);
452 			kunmap_atomic(buffer);
453 			local_irq_restore(flags);
454 
455 			size -= sz;
456 			pfn++;
457 			vaddr += sz;
458 			offset = 0;
459 		}
460 	} else if (dir == DMA_TO_DEVICE) {
461 		memcpy(vaddr, phys_to_virt(orig_addr), size);
462 	} else {
463 		memcpy(phys_to_virt(orig_addr), vaddr, size);
464 	}
465 }
466 
467 #define slot_addr(start, idx)	((start) + ((idx) << IO_TLB_SHIFT))
468 
469 /*
470  * Carefully handle integer overflow which can occur when boundary_mask == ~0UL.
471  */
472 static inline unsigned long get_max_slots(unsigned long boundary_mask)
473 {
474 	if (boundary_mask == ~0UL)
475 		return 1UL << (BITS_PER_LONG - IO_TLB_SHIFT);
476 	return nr_slots(boundary_mask + 1);
477 }
478 
479 static unsigned int wrap_index(struct io_tlb_mem *mem, unsigned int index)
480 {
481 	if (index >= mem->nslabs)
482 		return 0;
483 	return index;
484 }
485 
486 /*
487  * Find a suitable number of IO TLB entries size that will fit this request and
488  * allocate a buffer from that IO TLB pool.
489  */
490 static int swiotlb_find_slots(struct device *dev, phys_addr_t orig_addr,
491 			      size_t alloc_size, unsigned int alloc_align_mask)
492 {
493 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
494 	unsigned long boundary_mask = dma_get_seg_boundary(dev);
495 	dma_addr_t tbl_dma_addr =
496 		phys_to_dma_unencrypted(dev, mem->start) & boundary_mask;
497 	unsigned long max_slots = get_max_slots(boundary_mask);
498 	unsigned int iotlb_align_mask =
499 		dma_get_min_align_mask(dev) & ~(IO_TLB_SIZE - 1);
500 	unsigned int nslots = nr_slots(alloc_size), stride;
501 	unsigned int index, wrap, count = 0, i;
502 	unsigned int offset = swiotlb_align_offset(dev, orig_addr);
503 	unsigned long flags;
504 
505 	BUG_ON(!nslots);
506 
507 	/*
508 	 * For mappings with an alignment requirement don't bother looping to
509 	 * unaligned slots once we found an aligned one.  For allocations of
510 	 * PAGE_SIZE or larger only look for page aligned allocations.
511 	 */
512 	stride = (iotlb_align_mask >> IO_TLB_SHIFT) + 1;
513 	if (alloc_size >= PAGE_SIZE)
514 		stride = max(stride, stride << (PAGE_SHIFT - IO_TLB_SHIFT));
515 	stride = max(stride, (alloc_align_mask >> IO_TLB_SHIFT) + 1);
516 
517 	spin_lock_irqsave(&mem->lock, flags);
518 	if (unlikely(nslots > mem->nslabs - mem->used))
519 		goto not_found;
520 
521 	index = wrap = wrap_index(mem, ALIGN(mem->index, stride));
522 	do {
523 		if (orig_addr &&
524 		    (slot_addr(tbl_dma_addr, index) & iotlb_align_mask) !=
525 			    (orig_addr & iotlb_align_mask)) {
526 			index = wrap_index(mem, index + 1);
527 			continue;
528 		}
529 
530 		/*
531 		 * If we find a slot that indicates we have 'nslots' number of
532 		 * contiguous buffers, we allocate the buffers from that slot
533 		 * and mark the entries as '0' indicating unavailable.
534 		 */
535 		if (!iommu_is_span_boundary(index, nslots,
536 					    nr_slots(tbl_dma_addr),
537 					    max_slots)) {
538 			if (mem->slots[index].list >= nslots)
539 				goto found;
540 		}
541 		index = wrap_index(mem, index + stride);
542 	} while (index != wrap);
543 
544 not_found:
545 	spin_unlock_irqrestore(&mem->lock, flags);
546 	return -1;
547 
548 found:
549 	for (i = index; i < index + nslots; i++) {
550 		mem->slots[i].list = 0;
551 		mem->slots[i].alloc_size =
552 			alloc_size - (offset + ((i - index) << IO_TLB_SHIFT));
553 	}
554 	for (i = index - 1;
555 	     io_tlb_offset(i) != IO_TLB_SEGSIZE - 1 &&
556 	     mem->slots[i].list; i--)
557 		mem->slots[i].list = ++count;
558 
559 	/*
560 	 * Update the indices to avoid searching in the next round.
561 	 */
562 	if (index + nslots < mem->nslabs)
563 		mem->index = index + nslots;
564 	else
565 		mem->index = 0;
566 	mem->used += nslots;
567 
568 	spin_unlock_irqrestore(&mem->lock, flags);
569 	return index;
570 }
571 
572 phys_addr_t swiotlb_tbl_map_single(struct device *dev, phys_addr_t orig_addr,
573 		size_t mapping_size, size_t alloc_size,
574 		unsigned int alloc_align_mask, enum dma_data_direction dir,
575 		unsigned long attrs)
576 {
577 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
578 	unsigned int offset = swiotlb_align_offset(dev, orig_addr);
579 	unsigned int i;
580 	int index;
581 	phys_addr_t tlb_addr;
582 
583 	if (!mem)
584 		panic("Can not allocate SWIOTLB buffer earlier and can't now provide you with the DMA bounce buffer");
585 
586 	if (cc_platform_has(CC_ATTR_MEM_ENCRYPT))
587 		pr_warn_once("Memory encryption is active and system is using DMA bounce buffers\n");
588 
589 	if (mapping_size > alloc_size) {
590 		dev_warn_once(dev, "Invalid sizes (mapping: %zd bytes, alloc: %zd bytes)",
591 			      mapping_size, alloc_size);
592 		return (phys_addr_t)DMA_MAPPING_ERROR;
593 	}
594 
595 	index = swiotlb_find_slots(dev, orig_addr,
596 				   alloc_size + offset, alloc_align_mask);
597 	if (index == -1) {
598 		if (!(attrs & DMA_ATTR_NO_WARN))
599 			dev_warn_ratelimited(dev,
600 	"swiotlb buffer is full (sz: %zd bytes), total %lu (slots), used %lu (slots)\n",
601 				 alloc_size, mem->nslabs, mem->used);
602 		return (phys_addr_t)DMA_MAPPING_ERROR;
603 	}
604 
605 	/*
606 	 * Save away the mapping from the original address to the DMA address.
607 	 * This is needed when we sync the memory.  Then we sync the buffer if
608 	 * needed.
609 	 */
610 	for (i = 0; i < nr_slots(alloc_size + offset); i++)
611 		mem->slots[index + i].orig_addr = slot_addr(orig_addr, i);
612 	tlb_addr = slot_addr(mem->start, index) + offset;
613 	/*
614 	 * When dir == DMA_FROM_DEVICE we could omit the copy from the orig
615 	 * to the tlb buffer, if we knew for sure the device will
616 	 * overwirte the entire current content. But we don't. Thus
617 	 * unconditional bounce may prevent leaking swiotlb content (i.e.
618 	 * kernel memory) to user-space.
619 	 */
620 	swiotlb_bounce(dev, tlb_addr, mapping_size, DMA_TO_DEVICE);
621 	return tlb_addr;
622 }
623 
624 static void swiotlb_release_slots(struct device *dev, phys_addr_t tlb_addr)
625 {
626 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
627 	unsigned long flags;
628 	unsigned int offset = swiotlb_align_offset(dev, tlb_addr);
629 	int index = (tlb_addr - offset - mem->start) >> IO_TLB_SHIFT;
630 	int nslots = nr_slots(mem->slots[index].alloc_size + offset);
631 	int count, i;
632 
633 	/*
634 	 * Return the buffer to the free list by setting the corresponding
635 	 * entries to indicate the number of contiguous entries available.
636 	 * While returning the entries to the free list, we merge the entries
637 	 * with slots below and above the pool being returned.
638 	 */
639 	spin_lock_irqsave(&mem->lock, flags);
640 	if (index + nslots < ALIGN(index + 1, IO_TLB_SEGSIZE))
641 		count = mem->slots[index + nslots].list;
642 	else
643 		count = 0;
644 
645 	/*
646 	 * Step 1: return the slots to the free list, merging the slots with
647 	 * superceeding slots
648 	 */
649 	for (i = index + nslots - 1; i >= index; i--) {
650 		mem->slots[i].list = ++count;
651 		mem->slots[i].orig_addr = INVALID_PHYS_ADDR;
652 		mem->slots[i].alloc_size = 0;
653 	}
654 
655 	/*
656 	 * Step 2: merge the returned slots with the preceding slots, if
657 	 * available (non zero)
658 	 */
659 	for (i = index - 1;
660 	     io_tlb_offset(i) != IO_TLB_SEGSIZE - 1 && mem->slots[i].list;
661 	     i--)
662 		mem->slots[i].list = ++count;
663 	mem->used -= nslots;
664 	spin_unlock_irqrestore(&mem->lock, flags);
665 }
666 
667 /*
668  * tlb_addr is the physical address of the bounce buffer to unmap.
669  */
670 void swiotlb_tbl_unmap_single(struct device *dev, phys_addr_t tlb_addr,
671 			      size_t mapping_size, enum dma_data_direction dir,
672 			      unsigned long attrs)
673 {
674 	/*
675 	 * First, sync the memory before unmapping the entry
676 	 */
677 	if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
678 	    (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL))
679 		swiotlb_bounce(dev, tlb_addr, mapping_size, DMA_FROM_DEVICE);
680 
681 	swiotlb_release_slots(dev, tlb_addr);
682 }
683 
684 void swiotlb_sync_single_for_device(struct device *dev, phys_addr_t tlb_addr,
685 		size_t size, enum dma_data_direction dir)
686 {
687 	if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL)
688 		swiotlb_bounce(dev, tlb_addr, size, DMA_TO_DEVICE);
689 	else
690 		BUG_ON(dir != DMA_FROM_DEVICE);
691 }
692 
693 void swiotlb_sync_single_for_cpu(struct device *dev, phys_addr_t tlb_addr,
694 		size_t size, enum dma_data_direction dir)
695 {
696 	if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
697 		swiotlb_bounce(dev, tlb_addr, size, DMA_FROM_DEVICE);
698 	else
699 		BUG_ON(dir != DMA_TO_DEVICE);
700 }
701 
702 /*
703  * Create a swiotlb mapping for the buffer at @paddr, and in case of DMAing
704  * to the device copy the data into it as well.
705  */
706 dma_addr_t swiotlb_map(struct device *dev, phys_addr_t paddr, size_t size,
707 		enum dma_data_direction dir, unsigned long attrs)
708 {
709 	phys_addr_t swiotlb_addr;
710 	dma_addr_t dma_addr;
711 
712 	trace_swiotlb_bounced(dev, phys_to_dma(dev, paddr), size);
713 
714 	swiotlb_addr = swiotlb_tbl_map_single(dev, paddr, size, size, 0, dir,
715 			attrs);
716 	if (swiotlb_addr == (phys_addr_t)DMA_MAPPING_ERROR)
717 		return DMA_MAPPING_ERROR;
718 
719 	/* Ensure that the address returned is DMA'ble */
720 	dma_addr = phys_to_dma_unencrypted(dev, swiotlb_addr);
721 	if (unlikely(!dma_capable(dev, dma_addr, size, true))) {
722 		swiotlb_tbl_unmap_single(dev, swiotlb_addr, size, dir,
723 			attrs | DMA_ATTR_SKIP_CPU_SYNC);
724 		dev_WARN_ONCE(dev, 1,
725 			"swiotlb addr %pad+%zu overflow (mask %llx, bus limit %llx).\n",
726 			&dma_addr, size, *dev->dma_mask, dev->bus_dma_limit);
727 		return DMA_MAPPING_ERROR;
728 	}
729 
730 	if (!dev_is_dma_coherent(dev) && !(attrs & DMA_ATTR_SKIP_CPU_SYNC))
731 		arch_sync_dma_for_device(swiotlb_addr, size, dir);
732 	return dma_addr;
733 }
734 
735 size_t swiotlb_max_mapping_size(struct device *dev)
736 {
737 	int min_align_mask = dma_get_min_align_mask(dev);
738 	int min_align = 0;
739 
740 	/*
741 	 * swiotlb_find_slots() skips slots according to
742 	 * min align mask. This affects max mapping size.
743 	 * Take it into acount here.
744 	 */
745 	if (min_align_mask)
746 		min_align = roundup(min_align_mask, IO_TLB_SIZE);
747 
748 	return ((size_t)IO_TLB_SIZE) * IO_TLB_SEGSIZE - min_align;
749 }
750 
751 bool is_swiotlb_active(struct device *dev)
752 {
753 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
754 
755 	return mem && mem->nslabs;
756 }
757 EXPORT_SYMBOL_GPL(is_swiotlb_active);
758 
759 static void swiotlb_create_debugfs_files(struct io_tlb_mem *mem,
760 					 const char *dirname)
761 {
762 	mem->debugfs = debugfs_create_dir(dirname, io_tlb_default_mem.debugfs);
763 	if (!mem->nslabs)
764 		return;
765 
766 	debugfs_create_ulong("io_tlb_nslabs", 0400, mem->debugfs, &mem->nslabs);
767 	debugfs_create_ulong("io_tlb_used", 0400, mem->debugfs, &mem->used);
768 }
769 
770 static int __init __maybe_unused swiotlb_create_default_debugfs(void)
771 {
772 	swiotlb_create_debugfs_files(&io_tlb_default_mem, "swiotlb");
773 	return 0;
774 }
775 
776 #ifdef CONFIG_DEBUG_FS
777 late_initcall(swiotlb_create_default_debugfs);
778 #endif
779 
780 #ifdef CONFIG_DMA_RESTRICTED_POOL
781 
782 struct page *swiotlb_alloc(struct device *dev, size_t size)
783 {
784 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
785 	phys_addr_t tlb_addr;
786 	int index;
787 
788 	if (!mem)
789 		return NULL;
790 
791 	index = swiotlb_find_slots(dev, 0, size, 0);
792 	if (index == -1)
793 		return NULL;
794 
795 	tlb_addr = slot_addr(mem->start, index);
796 
797 	return pfn_to_page(PFN_DOWN(tlb_addr));
798 }
799 
800 bool swiotlb_free(struct device *dev, struct page *page, size_t size)
801 {
802 	phys_addr_t tlb_addr = page_to_phys(page);
803 
804 	if (!is_swiotlb_buffer(dev, tlb_addr))
805 		return false;
806 
807 	swiotlb_release_slots(dev, tlb_addr);
808 
809 	return true;
810 }
811 
812 static int rmem_swiotlb_device_init(struct reserved_mem *rmem,
813 				    struct device *dev)
814 {
815 	struct io_tlb_mem *mem = rmem->priv;
816 	unsigned long nslabs = rmem->size >> IO_TLB_SHIFT;
817 
818 	/*
819 	 * Since multiple devices can share the same pool, the private data,
820 	 * io_tlb_mem struct, will be initialized by the first device attached
821 	 * to it.
822 	 */
823 	if (!mem) {
824 		mem = kzalloc(sizeof(*mem), GFP_KERNEL);
825 		if (!mem)
826 			return -ENOMEM;
827 
828 		mem->slots = kcalloc(nslabs, sizeof(*mem->slots), GFP_KERNEL);
829 		if (!mem->slots) {
830 			kfree(mem);
831 			return -ENOMEM;
832 		}
833 
834 		set_memory_decrypted((unsigned long)phys_to_virt(rmem->base),
835 				     rmem->size >> PAGE_SHIFT);
836 		swiotlb_init_io_tlb_mem(mem, rmem->base, nslabs, SWIOTLB_FORCE,
837 				false);
838 		mem->for_alloc = true;
839 
840 		rmem->priv = mem;
841 
842 		swiotlb_create_debugfs_files(mem, rmem->name);
843 	}
844 
845 	dev->dma_io_tlb_mem = mem;
846 
847 	return 0;
848 }
849 
850 static void rmem_swiotlb_device_release(struct reserved_mem *rmem,
851 					struct device *dev)
852 {
853 	dev->dma_io_tlb_mem = &io_tlb_default_mem;
854 }
855 
856 static const struct reserved_mem_ops rmem_swiotlb_ops = {
857 	.device_init = rmem_swiotlb_device_init,
858 	.device_release = rmem_swiotlb_device_release,
859 };
860 
861 static int __init rmem_swiotlb_setup(struct reserved_mem *rmem)
862 {
863 	unsigned long node = rmem->fdt_node;
864 
865 	if (of_get_flat_dt_prop(node, "reusable", NULL) ||
866 	    of_get_flat_dt_prop(node, "linux,cma-default", NULL) ||
867 	    of_get_flat_dt_prop(node, "linux,dma-default", NULL) ||
868 	    of_get_flat_dt_prop(node, "no-map", NULL))
869 		return -EINVAL;
870 
871 	if (PageHighMem(pfn_to_page(PHYS_PFN(rmem->base)))) {
872 		pr_err("Restricted DMA pool must be accessible within the linear mapping.");
873 		return -EINVAL;
874 	}
875 
876 	rmem->ops = &rmem_swiotlb_ops;
877 	pr_info("Reserved memory: created restricted DMA pool at %pa, size %ld MiB\n",
878 		&rmem->base, (unsigned long)rmem->size / SZ_1M);
879 	return 0;
880 }
881 
882 RESERVEDMEM_OF_DECLARE(dma, "restricted-dma-pool", rmem_swiotlb_setup);
883 #endif /* CONFIG_DMA_RESTRICTED_POOL */
884