xref: /linux/kernel/dma/swiotlb.c (revision 3f70356edf5611c28a68d8d5a9c2b442c9eb81e6)
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, 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 	if (swiotlb_force_bounce)
207 		mem->force_bounce = true;
208 
209 	spin_lock_init(&mem->lock);
210 	for (i = 0; i < mem->nslabs; i++) {
211 		mem->slots[i].list = IO_TLB_SEGSIZE - io_tlb_offset(i);
212 		mem->slots[i].orig_addr = INVALID_PHYS_ADDR;
213 		mem->slots[i].alloc_size = 0;
214 	}
215 
216 	/*
217 	 * If swiotlb_unencrypted_base is set, the bounce buffer memory will
218 	 * be remapped and cleared in swiotlb_update_mem_attributes.
219 	 */
220 	if (swiotlb_unencrypted_base)
221 		return;
222 
223 	memset(vaddr, 0, bytes);
224 	mem->vaddr = vaddr;
225 	return;
226 }
227 
228 int __init swiotlb_init_with_tbl(char *tlb, unsigned long nslabs,
229 		unsigned int flags)
230 {
231 	struct io_tlb_mem *mem = &io_tlb_default_mem;
232 	size_t alloc_size;
233 
234 	if (swiotlb_force_disable)
235 		return 0;
236 
237 	/* protect against double initialization */
238 	if (WARN_ON_ONCE(mem->nslabs))
239 		return -ENOMEM;
240 
241 	alloc_size = PAGE_ALIGN(array_size(sizeof(*mem->slots), nslabs));
242 	mem->slots = memblock_alloc(alloc_size, PAGE_SIZE);
243 	if (!mem->slots)
244 		panic("%s: Failed to allocate %zu bytes align=0x%lx\n",
245 		      __func__, alloc_size, PAGE_SIZE);
246 
247 	swiotlb_init_io_tlb_mem(mem, __pa(tlb), nslabs, false);
248 	mem->force_bounce = flags & SWIOTLB_FORCE;
249 
250 	if (flags & SWIOTLB_VERBOSE)
251 		swiotlb_print_info();
252 	return 0;
253 }
254 
255 /*
256  * Statically reserve bounce buffer space and initialize bounce buffer data
257  * structures for the software IO TLB used to implement the DMA API.
258  */
259 void __init swiotlb_init_remap(bool addressing_limit, unsigned int flags,
260 		int (*remap)(void *tlb, unsigned long nslabs))
261 {
262 	unsigned long nslabs = default_nslabs;
263 	size_t bytes;
264 	void *tlb;
265 
266 	if (!addressing_limit && !swiotlb_force_bounce)
267 		return;
268 	if (swiotlb_force_disable)
269 		return;
270 
271 	/*
272 	 * By default allocate the bounce buffer memory from low memory, but
273 	 * allow to pick a location everywhere for hypervisors with guest
274 	 * memory encryption.
275 	 */
276 retry:
277 	bytes = PAGE_ALIGN(default_nslabs << IO_TLB_SHIFT);
278 	if (flags & SWIOTLB_ANY)
279 		tlb = memblock_alloc(bytes, PAGE_SIZE);
280 	else
281 		tlb = memblock_alloc_low(bytes, PAGE_SIZE);
282 	if (!tlb)
283 		goto fail;
284 	if (remap && remap(tlb, nslabs) < 0) {
285 		memblock_free(tlb, PAGE_ALIGN(bytes));
286 
287 		nslabs = ALIGN(nslabs >> 1, IO_TLB_SEGSIZE);
288 		if (nslabs < IO_TLB_MIN_SLABS)
289 			panic("%s: Failed to remap %zu bytes\n",
290 			      __func__, bytes);
291 		goto retry;
292 	}
293 	if (swiotlb_init_with_tbl(tlb, default_nslabs, flags))
294 		goto fail_free_mem;
295 	return;
296 
297 fail_free_mem:
298 	memblock_free(tlb, bytes);
299 fail:
300 	pr_warn("Cannot allocate buffer");
301 }
302 
303 void __init swiotlb_init(bool addressing_limit, unsigned int flags)
304 {
305 	return swiotlb_init_remap(addressing_limit, flags, NULL);
306 }
307 
308 /*
309  * Systems with larger DMA zones (those that don't support ISA) can
310  * initialize the swiotlb later using the slab allocator if needed.
311  * This should be just like above, but with some error catching.
312  */
313 int swiotlb_init_late(size_t size, gfp_t gfp_mask,
314 		int (*remap)(void *tlb, unsigned long nslabs))
315 {
316 	unsigned long nslabs = ALIGN(size >> IO_TLB_SHIFT, IO_TLB_SEGSIZE);
317 	unsigned long bytes;
318 	unsigned char *vstart = NULL;
319 	unsigned int order;
320 	int rc = 0;
321 
322 	if (swiotlb_force_disable)
323 		return 0;
324 
325 retry:
326 	order = get_order(nslabs << IO_TLB_SHIFT);
327 	nslabs = SLABS_PER_PAGE << order;
328 	bytes = nslabs << IO_TLB_SHIFT;
329 
330 	while ((SLABS_PER_PAGE << order) > IO_TLB_MIN_SLABS) {
331 		vstart = (void *)__get_free_pages(gfp_mask | __GFP_NOWARN,
332 						  order);
333 		if (vstart)
334 			break;
335 		order--;
336 	}
337 
338 	if (!vstart)
339 		return -ENOMEM;
340 
341 	if (order != get_order(bytes)) {
342 		pr_warn("only able to allocate %ld MB\n",
343 			(PAGE_SIZE << order) >> 20);
344 		nslabs = SLABS_PER_PAGE << order;
345 	}
346 	if (remap)
347 		rc = remap(vstart, nslabs);
348 	if (rc) {
349 		free_pages((unsigned long)vstart, order);
350 
351 		nslabs = ALIGN(nslabs >> 1, IO_TLB_SEGSIZE);
352 		if (nslabs < IO_TLB_MIN_SLABS)
353 			return rc;
354 		goto retry;
355 	}
356 	rc = swiotlb_late_init_with_tbl(vstart, nslabs);
357 	if (rc)
358 		free_pages((unsigned long)vstart, order);
359 
360 	return rc;
361 }
362 
363 int
364 swiotlb_late_init_with_tbl(char *tlb, unsigned long nslabs)
365 {
366 	struct io_tlb_mem *mem = &io_tlb_default_mem;
367 	unsigned long bytes = nslabs << IO_TLB_SHIFT;
368 
369 	if (swiotlb_force_disable)
370 		return 0;
371 
372 	/* protect against double initialization */
373 	if (WARN_ON_ONCE(mem->nslabs))
374 		return -ENOMEM;
375 
376 	mem->slots = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
377 		get_order(array_size(sizeof(*mem->slots), nslabs)));
378 	if (!mem->slots)
379 		return -ENOMEM;
380 
381 	set_memory_decrypted((unsigned long)tlb, bytes >> PAGE_SHIFT);
382 	swiotlb_init_io_tlb_mem(mem, virt_to_phys(tlb), nslabs, true);
383 
384 	swiotlb_print_info();
385 	return 0;
386 }
387 
388 void __init swiotlb_exit(void)
389 {
390 	struct io_tlb_mem *mem = &io_tlb_default_mem;
391 	unsigned long tbl_vaddr;
392 	size_t tbl_size, slots_size;
393 
394 	if (swiotlb_force_bounce)
395 		return;
396 
397 	if (!mem->nslabs)
398 		return;
399 
400 	pr_info("tearing down default memory pool\n");
401 	tbl_vaddr = (unsigned long)phys_to_virt(mem->start);
402 	tbl_size = PAGE_ALIGN(mem->end - mem->start);
403 	slots_size = PAGE_ALIGN(array_size(sizeof(*mem->slots), mem->nslabs));
404 
405 	set_memory_encrypted(tbl_vaddr, tbl_size >> PAGE_SHIFT);
406 	if (mem->late_alloc) {
407 		free_pages(tbl_vaddr, get_order(tbl_size));
408 		free_pages((unsigned long)mem->slots, get_order(slots_size));
409 	} else {
410 		memblock_free_late(mem->start, tbl_size);
411 		memblock_free_late(__pa(mem->slots), slots_size);
412 	}
413 
414 	memset(mem, 0, sizeof(*mem));
415 }
416 
417 /*
418  * Return the offset into a iotlb slot required to keep the device happy.
419  */
420 static unsigned int swiotlb_align_offset(struct device *dev, u64 addr)
421 {
422 	return addr & dma_get_min_align_mask(dev) & (IO_TLB_SIZE - 1);
423 }
424 
425 /*
426  * Bounce: copy the swiotlb buffer from or back to the original dma location
427  */
428 static void swiotlb_bounce(struct device *dev, phys_addr_t tlb_addr, size_t size,
429 			   enum dma_data_direction dir)
430 {
431 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
432 	int index = (tlb_addr - mem->start) >> IO_TLB_SHIFT;
433 	phys_addr_t orig_addr = mem->slots[index].orig_addr;
434 	size_t alloc_size = mem->slots[index].alloc_size;
435 	unsigned long pfn = PFN_DOWN(orig_addr);
436 	unsigned char *vaddr = mem->vaddr + tlb_addr - mem->start;
437 	unsigned int tlb_offset, orig_addr_offset;
438 
439 	if (orig_addr == INVALID_PHYS_ADDR)
440 		return;
441 
442 	tlb_offset = tlb_addr & (IO_TLB_SIZE - 1);
443 	orig_addr_offset = swiotlb_align_offset(dev, orig_addr);
444 	if (tlb_offset < orig_addr_offset) {
445 		dev_WARN_ONCE(dev, 1,
446 			"Access before mapping start detected. orig offset %u, requested offset %u.\n",
447 			orig_addr_offset, tlb_offset);
448 		return;
449 	}
450 
451 	tlb_offset -= orig_addr_offset;
452 	if (tlb_offset > alloc_size) {
453 		dev_WARN_ONCE(dev, 1,
454 			"Buffer overflow detected. Allocation size: %zu. Mapping size: %zu+%u.\n",
455 			alloc_size, size, tlb_offset);
456 		return;
457 	}
458 
459 	orig_addr += tlb_offset;
460 	alloc_size -= tlb_offset;
461 
462 	if (size > alloc_size) {
463 		dev_WARN_ONCE(dev, 1,
464 			"Buffer overflow detected. Allocation size: %zu. Mapping size: %zu.\n",
465 			alloc_size, size);
466 		size = alloc_size;
467 	}
468 
469 	if (PageHighMem(pfn_to_page(pfn))) {
470 		/* The buffer does not have a mapping.  Map it in and copy */
471 		unsigned int offset = orig_addr & ~PAGE_MASK;
472 		char *buffer;
473 		unsigned int sz = 0;
474 		unsigned long flags;
475 
476 		while (size) {
477 			sz = min_t(size_t, PAGE_SIZE - offset, size);
478 
479 			local_irq_save(flags);
480 			buffer = kmap_atomic(pfn_to_page(pfn));
481 			if (dir == DMA_TO_DEVICE)
482 				memcpy(vaddr, buffer + offset, sz);
483 			else
484 				memcpy(buffer + offset, vaddr, sz);
485 			kunmap_atomic(buffer);
486 			local_irq_restore(flags);
487 
488 			size -= sz;
489 			pfn++;
490 			vaddr += sz;
491 			offset = 0;
492 		}
493 	} else if (dir == DMA_TO_DEVICE) {
494 		memcpy(vaddr, phys_to_virt(orig_addr), size);
495 	} else {
496 		memcpy(phys_to_virt(orig_addr), vaddr, size);
497 	}
498 }
499 
500 #define slot_addr(start, idx)	((start) + ((idx) << IO_TLB_SHIFT))
501 
502 /*
503  * Carefully handle integer overflow which can occur when boundary_mask == ~0UL.
504  */
505 static inline unsigned long get_max_slots(unsigned long boundary_mask)
506 {
507 	if (boundary_mask == ~0UL)
508 		return 1UL << (BITS_PER_LONG - IO_TLB_SHIFT);
509 	return nr_slots(boundary_mask + 1);
510 }
511 
512 static unsigned int wrap_index(struct io_tlb_mem *mem, unsigned int index)
513 {
514 	if (index >= mem->nslabs)
515 		return 0;
516 	return index;
517 }
518 
519 /*
520  * Find a suitable number of IO TLB entries size that will fit this request and
521  * allocate a buffer from that IO TLB pool.
522  */
523 static int swiotlb_find_slots(struct device *dev, phys_addr_t orig_addr,
524 			      size_t alloc_size, unsigned int alloc_align_mask)
525 {
526 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
527 	unsigned long boundary_mask = dma_get_seg_boundary(dev);
528 	dma_addr_t tbl_dma_addr =
529 		phys_to_dma_unencrypted(dev, mem->start) & boundary_mask;
530 	unsigned long max_slots = get_max_slots(boundary_mask);
531 	unsigned int iotlb_align_mask =
532 		dma_get_min_align_mask(dev) & ~(IO_TLB_SIZE - 1);
533 	unsigned int nslots = nr_slots(alloc_size), stride;
534 	unsigned int index, wrap, count = 0, i;
535 	unsigned int offset = swiotlb_align_offset(dev, orig_addr);
536 	unsigned long flags;
537 
538 	BUG_ON(!nslots);
539 
540 	/*
541 	 * For mappings with an alignment requirement don't bother looping to
542 	 * unaligned slots once we found an aligned one.  For allocations of
543 	 * PAGE_SIZE or larger only look for page aligned allocations.
544 	 */
545 	stride = (iotlb_align_mask >> IO_TLB_SHIFT) + 1;
546 	if (alloc_size >= PAGE_SIZE)
547 		stride = max(stride, stride << (PAGE_SHIFT - IO_TLB_SHIFT));
548 	stride = max(stride, (alloc_align_mask >> IO_TLB_SHIFT) + 1);
549 
550 	spin_lock_irqsave(&mem->lock, flags);
551 	if (unlikely(nslots > mem->nslabs - mem->used))
552 		goto not_found;
553 
554 	index = wrap = wrap_index(mem, ALIGN(mem->index, stride));
555 	do {
556 		if (orig_addr &&
557 		    (slot_addr(tbl_dma_addr, index) & iotlb_align_mask) !=
558 			    (orig_addr & iotlb_align_mask)) {
559 			index = wrap_index(mem, index + 1);
560 			continue;
561 		}
562 
563 		/*
564 		 * If we find a slot that indicates we have 'nslots' number of
565 		 * contiguous buffers, we allocate the buffers from that slot
566 		 * and mark the entries as '0' indicating unavailable.
567 		 */
568 		if (!iommu_is_span_boundary(index, nslots,
569 					    nr_slots(tbl_dma_addr),
570 					    max_slots)) {
571 			if (mem->slots[index].list >= nslots)
572 				goto found;
573 		}
574 		index = wrap_index(mem, index + stride);
575 	} while (index != wrap);
576 
577 not_found:
578 	spin_unlock_irqrestore(&mem->lock, flags);
579 	return -1;
580 
581 found:
582 	for (i = index; i < index + nslots; i++) {
583 		mem->slots[i].list = 0;
584 		mem->slots[i].alloc_size =
585 			alloc_size - (offset + ((i - index) << IO_TLB_SHIFT));
586 	}
587 	for (i = index - 1;
588 	     io_tlb_offset(i) != IO_TLB_SEGSIZE - 1 &&
589 	     mem->slots[i].list; i--)
590 		mem->slots[i].list = ++count;
591 
592 	/*
593 	 * Update the indices to avoid searching in the next round.
594 	 */
595 	if (index + nslots < mem->nslabs)
596 		mem->index = index + nslots;
597 	else
598 		mem->index = 0;
599 	mem->used += nslots;
600 
601 	spin_unlock_irqrestore(&mem->lock, flags);
602 	return index;
603 }
604 
605 phys_addr_t swiotlb_tbl_map_single(struct device *dev, phys_addr_t orig_addr,
606 		size_t mapping_size, size_t alloc_size,
607 		unsigned int alloc_align_mask, enum dma_data_direction dir,
608 		unsigned long attrs)
609 {
610 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
611 	unsigned int offset = swiotlb_align_offset(dev, orig_addr);
612 	unsigned int i;
613 	int index;
614 	phys_addr_t tlb_addr;
615 
616 	if (!mem)
617 		panic("Can not allocate SWIOTLB buffer earlier and can't now provide you with the DMA bounce buffer");
618 
619 	if (cc_platform_has(CC_ATTR_MEM_ENCRYPT))
620 		pr_warn_once("Memory encryption is active and system is using DMA bounce buffers\n");
621 
622 	if (mapping_size > alloc_size) {
623 		dev_warn_once(dev, "Invalid sizes (mapping: %zd bytes, alloc: %zd bytes)",
624 			      mapping_size, alloc_size);
625 		return (phys_addr_t)DMA_MAPPING_ERROR;
626 	}
627 
628 	index = swiotlb_find_slots(dev, orig_addr,
629 				   alloc_size + offset, alloc_align_mask);
630 	if (index == -1) {
631 		if (!(attrs & DMA_ATTR_NO_WARN))
632 			dev_warn_ratelimited(dev,
633 	"swiotlb buffer is full (sz: %zd bytes), total %lu (slots), used %lu (slots)\n",
634 				 alloc_size, mem->nslabs, mem->used);
635 		return (phys_addr_t)DMA_MAPPING_ERROR;
636 	}
637 
638 	/*
639 	 * Save away the mapping from the original address to the DMA address.
640 	 * This is needed when we sync the memory.  Then we sync the buffer if
641 	 * needed.
642 	 */
643 	for (i = 0; i < nr_slots(alloc_size + offset); i++)
644 		mem->slots[index + i].orig_addr = slot_addr(orig_addr, i);
645 	tlb_addr = slot_addr(mem->start, index) + offset;
646 	/*
647 	 * When dir == DMA_FROM_DEVICE we could omit the copy from the orig
648 	 * to the tlb buffer, if we knew for sure the device will
649 	 * overwirte the entire current content. But we don't. Thus
650 	 * unconditional bounce may prevent leaking swiotlb content (i.e.
651 	 * kernel memory) to user-space.
652 	 */
653 	swiotlb_bounce(dev, tlb_addr, mapping_size, DMA_TO_DEVICE);
654 	return tlb_addr;
655 }
656 
657 static void swiotlb_release_slots(struct device *dev, phys_addr_t tlb_addr)
658 {
659 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
660 	unsigned long flags;
661 	unsigned int offset = swiotlb_align_offset(dev, tlb_addr);
662 	int index = (tlb_addr - offset - mem->start) >> IO_TLB_SHIFT;
663 	int nslots = nr_slots(mem->slots[index].alloc_size + offset);
664 	int count, i;
665 
666 	/*
667 	 * Return the buffer to the free list by setting the corresponding
668 	 * entries to indicate the number of contiguous entries available.
669 	 * While returning the entries to the free list, we merge the entries
670 	 * with slots below and above the pool being returned.
671 	 */
672 	spin_lock_irqsave(&mem->lock, flags);
673 	if (index + nslots < ALIGN(index + 1, IO_TLB_SEGSIZE))
674 		count = mem->slots[index + nslots].list;
675 	else
676 		count = 0;
677 
678 	/*
679 	 * Step 1: return the slots to the free list, merging the slots with
680 	 * superceeding slots
681 	 */
682 	for (i = index + nslots - 1; i >= index; i--) {
683 		mem->slots[i].list = ++count;
684 		mem->slots[i].orig_addr = INVALID_PHYS_ADDR;
685 		mem->slots[i].alloc_size = 0;
686 	}
687 
688 	/*
689 	 * Step 2: merge the returned slots with the preceding slots, if
690 	 * available (non zero)
691 	 */
692 	for (i = index - 1;
693 	     io_tlb_offset(i) != IO_TLB_SEGSIZE - 1 && mem->slots[i].list;
694 	     i--)
695 		mem->slots[i].list = ++count;
696 	mem->used -= nslots;
697 	spin_unlock_irqrestore(&mem->lock, flags);
698 }
699 
700 /*
701  * tlb_addr is the physical address of the bounce buffer to unmap.
702  */
703 void swiotlb_tbl_unmap_single(struct device *dev, phys_addr_t tlb_addr,
704 			      size_t mapping_size, enum dma_data_direction dir,
705 			      unsigned long attrs)
706 {
707 	/*
708 	 * First, sync the memory before unmapping the entry
709 	 */
710 	if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
711 	    (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL))
712 		swiotlb_bounce(dev, tlb_addr, mapping_size, DMA_FROM_DEVICE);
713 
714 	swiotlb_release_slots(dev, tlb_addr);
715 }
716 
717 void swiotlb_sync_single_for_device(struct device *dev, phys_addr_t tlb_addr,
718 		size_t size, enum dma_data_direction dir)
719 {
720 	if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL)
721 		swiotlb_bounce(dev, tlb_addr, size, DMA_TO_DEVICE);
722 	else
723 		BUG_ON(dir != DMA_FROM_DEVICE);
724 }
725 
726 void swiotlb_sync_single_for_cpu(struct device *dev, phys_addr_t tlb_addr,
727 		size_t size, enum dma_data_direction dir)
728 {
729 	if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
730 		swiotlb_bounce(dev, tlb_addr, size, DMA_FROM_DEVICE);
731 	else
732 		BUG_ON(dir != DMA_TO_DEVICE);
733 }
734 
735 /*
736  * Create a swiotlb mapping for the buffer at @paddr, and in case of DMAing
737  * to the device copy the data into it as well.
738  */
739 dma_addr_t swiotlb_map(struct device *dev, phys_addr_t paddr, size_t size,
740 		enum dma_data_direction dir, unsigned long attrs)
741 {
742 	phys_addr_t swiotlb_addr;
743 	dma_addr_t dma_addr;
744 
745 	trace_swiotlb_bounced(dev, phys_to_dma(dev, paddr), size);
746 
747 	swiotlb_addr = swiotlb_tbl_map_single(dev, paddr, size, size, 0, dir,
748 			attrs);
749 	if (swiotlb_addr == (phys_addr_t)DMA_MAPPING_ERROR)
750 		return DMA_MAPPING_ERROR;
751 
752 	/* Ensure that the address returned is DMA'ble */
753 	dma_addr = phys_to_dma_unencrypted(dev, swiotlb_addr);
754 	if (unlikely(!dma_capable(dev, dma_addr, size, true))) {
755 		swiotlb_tbl_unmap_single(dev, swiotlb_addr, size, dir,
756 			attrs | DMA_ATTR_SKIP_CPU_SYNC);
757 		dev_WARN_ONCE(dev, 1,
758 			"swiotlb addr %pad+%zu overflow (mask %llx, bus limit %llx).\n",
759 			&dma_addr, size, *dev->dma_mask, dev->bus_dma_limit);
760 		return DMA_MAPPING_ERROR;
761 	}
762 
763 	if (!dev_is_dma_coherent(dev) && !(attrs & DMA_ATTR_SKIP_CPU_SYNC))
764 		arch_sync_dma_for_device(swiotlb_addr, size, dir);
765 	return dma_addr;
766 }
767 
768 size_t swiotlb_max_mapping_size(struct device *dev)
769 {
770 	return ((size_t)IO_TLB_SIZE) * IO_TLB_SEGSIZE;
771 }
772 
773 bool is_swiotlb_active(struct device *dev)
774 {
775 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
776 
777 	return mem && mem->nslabs;
778 }
779 EXPORT_SYMBOL_GPL(is_swiotlb_active);
780 
781 static void swiotlb_create_debugfs_files(struct io_tlb_mem *mem,
782 					 const char *dirname)
783 {
784 	mem->debugfs = debugfs_create_dir(dirname, io_tlb_default_mem.debugfs);
785 	if (!mem->nslabs)
786 		return;
787 
788 	debugfs_create_ulong("io_tlb_nslabs", 0400, mem->debugfs, &mem->nslabs);
789 	debugfs_create_ulong("io_tlb_used", 0400, mem->debugfs, &mem->used);
790 }
791 
792 static int __init __maybe_unused swiotlb_create_default_debugfs(void)
793 {
794 	swiotlb_create_debugfs_files(&io_tlb_default_mem, "swiotlb");
795 	return 0;
796 }
797 
798 #ifdef CONFIG_DEBUG_FS
799 late_initcall(swiotlb_create_default_debugfs);
800 #endif
801 
802 #ifdef CONFIG_DMA_RESTRICTED_POOL
803 
804 struct page *swiotlb_alloc(struct device *dev, size_t size)
805 {
806 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
807 	phys_addr_t tlb_addr;
808 	int index;
809 
810 	if (!mem)
811 		return NULL;
812 
813 	index = swiotlb_find_slots(dev, 0, size, 0);
814 	if (index == -1)
815 		return NULL;
816 
817 	tlb_addr = slot_addr(mem->start, index);
818 
819 	return pfn_to_page(PFN_DOWN(tlb_addr));
820 }
821 
822 bool swiotlb_free(struct device *dev, struct page *page, size_t size)
823 {
824 	phys_addr_t tlb_addr = page_to_phys(page);
825 
826 	if (!is_swiotlb_buffer(dev, tlb_addr))
827 		return false;
828 
829 	swiotlb_release_slots(dev, tlb_addr);
830 
831 	return true;
832 }
833 
834 static int rmem_swiotlb_device_init(struct reserved_mem *rmem,
835 				    struct device *dev)
836 {
837 	struct io_tlb_mem *mem = rmem->priv;
838 	unsigned long nslabs = rmem->size >> IO_TLB_SHIFT;
839 
840 	/*
841 	 * Since multiple devices can share the same pool, the private data,
842 	 * io_tlb_mem struct, will be initialized by the first device attached
843 	 * to it.
844 	 */
845 	if (!mem) {
846 		mem = kzalloc(sizeof(*mem), GFP_KERNEL);
847 		if (!mem)
848 			return -ENOMEM;
849 
850 		mem->slots = kcalloc(nslabs, sizeof(*mem->slots), GFP_KERNEL);
851 		if (!mem->slots) {
852 			kfree(mem);
853 			return -ENOMEM;
854 		}
855 
856 		set_memory_decrypted((unsigned long)phys_to_virt(rmem->base),
857 				     rmem->size >> PAGE_SHIFT);
858 		swiotlb_init_io_tlb_mem(mem, rmem->base, nslabs, false);
859 		mem->force_bounce = true;
860 		mem->for_alloc = true;
861 
862 		rmem->priv = mem;
863 
864 		swiotlb_create_debugfs_files(mem, rmem->name);
865 	}
866 
867 	dev->dma_io_tlb_mem = mem;
868 
869 	return 0;
870 }
871 
872 static void rmem_swiotlb_device_release(struct reserved_mem *rmem,
873 					struct device *dev)
874 {
875 	dev->dma_io_tlb_mem = &io_tlb_default_mem;
876 }
877 
878 static const struct reserved_mem_ops rmem_swiotlb_ops = {
879 	.device_init = rmem_swiotlb_device_init,
880 	.device_release = rmem_swiotlb_device_release,
881 };
882 
883 static int __init rmem_swiotlb_setup(struct reserved_mem *rmem)
884 {
885 	unsigned long node = rmem->fdt_node;
886 
887 	if (of_get_flat_dt_prop(node, "reusable", NULL) ||
888 	    of_get_flat_dt_prop(node, "linux,cma-default", NULL) ||
889 	    of_get_flat_dt_prop(node, "linux,dma-default", NULL) ||
890 	    of_get_flat_dt_prop(node, "no-map", NULL))
891 		return -EINVAL;
892 
893 	if (PageHighMem(pfn_to_page(PHYS_PFN(rmem->base)))) {
894 		pr_err("Restricted DMA pool must be accessible within the linear mapping.");
895 		return -EINVAL;
896 	}
897 
898 	rmem->ops = &rmem_swiotlb_ops;
899 	pr_info("Reserved memory: created restricted DMA pool at %pa, size %ld MiB\n",
900 		&rmem->base, (unsigned long)rmem->size / SZ_1M);
901 	return 0;
902 }
903 
904 RESERVEDMEM_OF_DECLARE(dma, "restricted-dma-pool", rmem_swiotlb_setup);
905 #endif /* CONFIG_DMA_RESTRICTED_POOL */
906