xref: /linux/kernel/dma/swiotlb.c (revision 906b6e1d8c782a8442b30bdf8b8992f5031ffc59)
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/kmsan-checks.h>
34 #include <linux/iommu-helper.h>
35 #include <linux/init.h>
36 #include <linux/memblock.h>
37 #include <linux/mm.h>
38 #include <linux/pfn.h>
39 #include <linux/rculist.h>
40 #include <linux/scatterlist.h>
41 #include <linux/set_memory.h>
42 #include <linux/spinlock.h>
43 #include <linux/string.h>
44 #include <linux/swiotlb.h>
45 #include <linux/types.h>
46 #ifdef CONFIG_DMA_RESTRICTED_POOL
47 #include <linux/of.h>
48 #include <linux/of_fdt.h>
49 #include <linux/of_reserved_mem.h>
50 #include <linux/slab.h>
51 #endif
52 
53 #define CREATE_TRACE_POINTS
54 #include <trace/events/swiotlb.h>
55 
56 #define SLABS_PER_PAGE (1 << (PAGE_SHIFT - IO_TLB_SHIFT))
57 
58 /*
59  * Minimum IO TLB size to bother booting with.  Systems with mainly
60  * 64bit capable cards will only lightly use the swiotlb.  If we can't
61  * allocate a contiguous 1MB, we're probably in trouble anyway.
62  */
63 #define IO_TLB_MIN_SLABS ((1<<20) >> IO_TLB_SHIFT)
64 
65 /**
66  * struct io_tlb_slot - IO TLB slot descriptor
67  * @orig_addr:	The original address corresponding to a mapped entry.
68  * @alloc_size:	Size of the allocated buffer.
69  * @list:	The free list describing the number of free entries available
70  *		from each index.
71  * @pad_slots:	Number of preceding padding slots. Valid only in the first
72  *		allocated non-padding slot.
73  */
74 struct io_tlb_slot {
75 	phys_addr_t orig_addr;
76 	size_t alloc_size;
77 	unsigned short list;
78 	unsigned short pad_slots;
79 };
80 
81 static bool swiotlb_force_bounce;
82 static bool swiotlb_force_disable;
83 
84 #ifdef CONFIG_SWIOTLB_DYNAMIC
85 
86 static void swiotlb_dyn_alloc(struct work_struct *work);
87 
88 static struct io_tlb_mem io_tlb_default_mem = {
89 	.lock = __SPIN_LOCK_UNLOCKED(io_tlb_default_mem.lock),
90 	.pools = LIST_HEAD_INIT(io_tlb_default_mem.pools),
91 	.dyn_alloc = __WORK_INITIALIZER(io_tlb_default_mem.dyn_alloc,
92 					swiotlb_dyn_alloc),
93 };
94 
95 #else  /* !CONFIG_SWIOTLB_DYNAMIC */
96 
97 static struct io_tlb_mem io_tlb_default_mem;
98 
99 #endif	/* CONFIG_SWIOTLB_DYNAMIC */
100 
101 static unsigned long default_nslabs = IO_TLB_DEFAULT_SIZE >> IO_TLB_SHIFT;
102 static unsigned long default_nareas;
103 static bool swiotlb_cmdline_size_set __initdata;
104 
105 /**
106  * struct io_tlb_area - IO TLB memory area descriptor
107  *
108  * This is a single area with a single lock.
109  *
110  * @used:	The number of used IO TLB block.
111  * @index:	The slot index to start searching in this area for next round.
112  * @lock:	The lock to protect the above data structures in the map and
113  *		unmap calls.
114  */
115 struct io_tlb_area {
116 	unsigned long used;
117 	unsigned int index;
118 	spinlock_t lock;
119 };
120 
121 /* Return a power-of-two number of slabs that can be split between areas. */
122 static unsigned long swiotlb_calc_nslabs(unsigned long size,
123 		unsigned long nareas)
124 {
125 	unsigned long nslabs;
126 
127 	nslabs = ALIGN(DIV_ROUND_UP(size, IO_TLB_SIZE), IO_TLB_SEGSIZE);
128 	if (nareas && nslabs < IO_TLB_SEGSIZE * nareas)
129 		nslabs = IO_TLB_SEGSIZE * nareas;
130 
131 	if (!is_power_of_2(nslabs))
132 		nslabs = roundup_pow_of_two(nslabs);
133 
134 	return nslabs;
135 }
136 
137 /**
138  * swiotlb_adjust_nareas() - adjust the number of areas and slots
139  * @nareas:	Desired number of areas. Zero is treated as 1.
140  *
141  * Adjust the default number of areas in a memory pool.
142  * The default size of the memory pool may also change to meet minimum area
143  * size requirements.
144  */
145 static void swiotlb_adjust_nareas(unsigned int nareas)
146 {
147 	unsigned long nslabs;
148 
149 	if (!nareas)
150 		nareas = 1;
151 	else if (!is_power_of_2(nareas))
152 		nareas = roundup_pow_of_two(nareas);
153 
154 	default_nareas = nareas;
155 
156 	pr_info("area num %d.\n", nareas);
157 	nslabs = swiotlb_calc_nslabs(default_nslabs << IO_TLB_SHIFT, nareas);
158 	if (nslabs != default_nslabs) {
159 		default_nslabs = nslabs;
160 		pr_info("SWIOTLB bounce buffer size roundup to %luMB",
161 			(default_nslabs << IO_TLB_SHIFT) >> 20);
162 	}
163 }
164 
165 /**
166  * limit_nareas() - get the maximum number of areas for a given memory pool size
167  * @nareas:	Desired number of areas.
168  * @nslots:	Total number of slots in the memory pool.
169  *
170  * Limit the number of areas to the maximum possible number of areas in
171  * a memory pool of the given size.
172  *
173  * Return: Maximum possible number of areas.
174  */
175 static unsigned int limit_nareas(unsigned int nareas, unsigned long nslots)
176 {
177 	if (nslots < nareas * IO_TLB_SEGSIZE)
178 		return nslots / IO_TLB_SEGSIZE;
179 	return nareas;
180 }
181 
182 #ifdef CONFIG_DEBUG_FS
183 /*
184  * Track the total used slots with a global atomic value in order to have
185  * correct information to determine the high water mark.
186  */
187 static void inc_used_and_hiwater_real(struct io_tlb_mem *mem,
188 				      unsigned int nslots)
189 {
190 	unsigned long old_hiwater, new_used;
191 
192 	new_used = atomic_long_add_return(nslots, &mem->total_used);
193 	old_hiwater = atomic_long_read(&mem->used_hiwater);
194 	do {
195 		if (new_used <= old_hiwater)
196 			break;
197 	} while (!atomic_long_try_cmpxchg(&mem->used_hiwater,
198 					  &old_hiwater, new_used));
199 }
200 
201 static void dec_used_real(struct io_tlb_mem *mem, unsigned int nslots)
202 {
203 	atomic_long_sub(nslots, &mem->total_used);
204 }
205 
206 static void inc_used_and_hiwater_nop(struct io_tlb_mem *mem,
207 				     unsigned int nslots)
208 {
209 }
210 static void dec_used_nop(struct io_tlb_mem *mem, unsigned int nslots)
211 {
212 }
213 
214 DEFINE_STATIC_CALL(swiotlb_inc_used, inc_used_and_hiwater_nop);
215 DEFINE_STATIC_CALL(swiotlb_dec_used, dec_used_nop);
216 
217 static __always_inline void inc_used_and_hiwater(struct io_tlb_mem *mem,
218 						  unsigned int nslots)
219 {
220 	static_call(swiotlb_inc_used)(mem, nslots);
221 }
222 
223 static __always_inline void dec_used(struct io_tlb_mem *mem,
224 				     unsigned int nslots)
225 {
226 	static_call(swiotlb_dec_used)(mem, nslots);
227 }
228 
229 static bool track_hiwater_enabled __read_mostly;
230 
231 #else
232 
233 static __always_inline void inc_used_and_hiwater(struct io_tlb_mem *mem,
234 						  unsigned int nslots)
235 {
236 }
237 
238 static __always_inline void dec_used(struct io_tlb_mem *mem,
239 				     unsigned int nslots)
240 {
241 }
242 #endif
243 
244 /*
245  * The tracking of used slots high watermark can be enabled
246  * by appending "track_hiwater" to the swiotlb= boot parameter.
247  * When disabled the tracking functions are no-ops with near-zero
248  * overhead via static_call.
249  */
250 static int __init
251 setup_io_tlb_npages(char *str)
252 {
253 	if (isdigit(*str)) {
254 		/* avoid tail segment of size < IO_TLB_SEGSIZE */
255 		default_nslabs =
256 			ALIGN(simple_strtoul(str, &str, 0), IO_TLB_SEGSIZE);
257 		swiotlb_cmdline_size_set = true;
258 	}
259 	if (*str == ',')
260 		++str;
261 	if (isdigit(*str))
262 		swiotlb_adjust_nareas(simple_strtoul(str, &str, 0));
263 	if (*str == ',')
264 		++str;
265 	if (!strncmp(str, "force", 5)) {
266 		swiotlb_force_bounce = true;
267 		str += 5;
268 	} else if (!strncmp(str, "noforce", 7)) {
269 		swiotlb_force_disable = true;
270 		str += 7;
271 	}
272 
273 #ifdef CONFIG_DEBUG_FS
274 	if (*str == ',')
275 		++str;
276 	if (!strncmp(str, "track_hiwater", 13)) {
277 		track_hiwater_enabled = true;
278 		static_call_update(swiotlb_inc_used,
279 					inc_used_and_hiwater_real);
280 		static_call_update(swiotlb_dec_used, dec_used_real);
281 	}
282 #endif
283 
284 	return 0;
285 }
286 early_param("swiotlb", setup_io_tlb_npages);
287 
288 unsigned long swiotlb_default_pool_size(void)
289 {
290 	return default_nslabs << IO_TLB_SHIFT;
291 }
292 
293 void __init swiotlb_adjust_size(unsigned long size)
294 {
295 	/*
296 	 * If swiotlb parameter has not been specified, give a chance to
297 	 * architectures such as those supporting memory encryption to
298 	 * adjust/expand SWIOTLB size for their use.
299 	 */
300 	if (swiotlb_cmdline_size_set)
301 		return;
302 
303 	default_nslabs = swiotlb_calc_nslabs(size, default_nareas);
304 	size = default_nslabs << IO_TLB_SHIFT;
305 	pr_info("SWIOTLB bounce buffer size adjusted to %luMB", size >> 20);
306 }
307 
308 void swiotlb_print_info(void)
309 {
310 	struct io_tlb_pool *mem = &io_tlb_default_mem.defpool;
311 
312 	if (!mem->nslabs) {
313 		pr_warn("No low mem\n");
314 		return;
315 	}
316 
317 	pr_info("mapped [mem %pa-%pa] (%luMB)\n", &mem->start, &mem->end,
318 	       (mem->nslabs << IO_TLB_SHIFT) >> 20);
319 }
320 
321 static inline unsigned long io_tlb_offset(unsigned long val)
322 {
323 	return val & (IO_TLB_SEGSIZE - 1);
324 }
325 
326 static inline unsigned long nr_slots(u64 val)
327 {
328 	return DIV_ROUND_UP(val, IO_TLB_SIZE);
329 }
330 
331 static void swiotlb_mark_pool_used(struct io_tlb_pool *pool)
332 {
333 	unsigned long i;
334 
335 	for (i = 0; i < pool->nareas; i++) {
336 		pool->areas[i].index = 0;
337 		pool->areas[i].used = pool->area_nslabs;
338 	}
339 
340 	for (i = 0; i < pool->nslabs; i++) {
341 		pool->slots[i].list = 0;
342 		pool->slots[i].orig_addr = INVALID_PHYS_ADDR;
343 		pool->slots[i].alloc_size = 0;
344 		pool->slots[i].pad_slots = 0;
345 	}
346 }
347 
348 /*
349  * Early SWIOTLB allocation may be too early to allow an architecture to
350  * perform the desired operations.  This function allows the architecture to
351  * call SWIOTLB when the operations are possible.  It needs to be called
352  * before the SWIOTLB memory is used.
353  */
354 void __init swiotlb_update_mem_attributes(void)
355 {
356 	struct io_tlb_pool *mem = &io_tlb_default_mem.defpool;
357 	unsigned long bytes;
358 
359 	/*
360 	 * if platform support memory encryption, swiotlb buffers are
361 	 * shared by default.
362 	 */
363 	if (cc_platform_has(CC_ATTR_MEM_ENCRYPT))
364 		io_tlb_default_mem.cc_shared = true;
365 	else
366 		io_tlb_default_mem.cc_shared = false;
367 
368 	if (!mem->nslabs || mem->late_alloc)
369 		return;
370 	bytes = PAGE_ALIGN(mem->nslabs << IO_TLB_SHIFT);
371 
372 	if (io_tlb_default_mem.cc_shared) {
373 		int ret;
374 
375 		ret = set_memory_decrypted((unsigned long)mem->vaddr,
376 					   bytes >> PAGE_SHIFT);
377 		if (ret) {
378 			pr_warn("Failed to decrypt default memory pool, disabling it\n");
379 			swiotlb_mark_pool_used(mem);
380 		}
381 	}
382 }
383 
384 static void swiotlb_init_io_tlb_pool(struct io_tlb_pool *mem, phys_addr_t start,
385 		void *vaddr, unsigned long nslabs, bool late_alloc,
386 		unsigned int nareas)
387 {
388 	unsigned long bytes = nslabs << IO_TLB_SHIFT, i;
389 
390 	mem->nslabs = nslabs;
391 	mem->start = start;
392 	mem->end = mem->start + bytes;
393 	mem->late_alloc = late_alloc;
394 	mem->nareas = nareas;
395 	mem->area_nslabs = nslabs / mem->nareas;
396 
397 	for (i = 0; i < mem->nareas; i++) {
398 		spin_lock_init(&mem->areas[i].lock);
399 		mem->areas[i].index = 0;
400 		mem->areas[i].used = 0;
401 	}
402 
403 	for (i = 0; i < mem->nslabs; i++) {
404 		mem->slots[i].list = min(IO_TLB_SEGSIZE - io_tlb_offset(i),
405 					 mem->nslabs - i);
406 		mem->slots[i].orig_addr = INVALID_PHYS_ADDR;
407 		mem->slots[i].alloc_size = 0;
408 		mem->slots[i].pad_slots = 0;
409 	}
410 
411 	memset(vaddr, 0, bytes);
412 	mem->vaddr = vaddr;
413 	return;
414 }
415 
416 /**
417  * add_mem_pool() - add a memory pool to the allocator
418  * @mem:	Software IO TLB allocator.
419  * @pool:	Memory pool to be added.
420  */
421 static void add_mem_pool(struct io_tlb_mem *mem, struct io_tlb_pool *pool)
422 {
423 #ifdef CONFIG_SWIOTLB_DYNAMIC
424 	spin_lock(&mem->lock);
425 	list_add_rcu(&pool->node, &mem->pools);
426 	mem->nslabs += pool->nslabs;
427 	spin_unlock(&mem->lock);
428 #else
429 	mem->nslabs = pool->nslabs;
430 #endif
431 }
432 
433 static void __init *swiotlb_memblock_alloc(unsigned long nslabs,
434 		unsigned int flags,
435 		int (*remap)(void *tlb, unsigned long nslabs))
436 {
437 	size_t bytes = PAGE_ALIGN(nslabs << IO_TLB_SHIFT);
438 	void *tlb;
439 
440 	/*
441 	 * By default allocate the bounce buffer memory from low memory, but
442 	 * allow to pick a location everywhere for hypervisors with guest
443 	 * memory encryption.
444 	 */
445 	if (flags & SWIOTLB_ANY)
446 		tlb = memblock_alloc(bytes, PAGE_SIZE);
447 	else
448 		tlb = memblock_alloc_low(bytes, PAGE_SIZE);
449 
450 	if (!tlb) {
451 		pr_warn("%s: Failed to allocate %zu bytes tlb structure\n",
452 			__func__, bytes);
453 		return NULL;
454 	}
455 
456 	if (remap && remap(tlb, nslabs) < 0) {
457 		memblock_free(tlb, PAGE_ALIGN(bytes));
458 		pr_warn("%s: Failed to remap %zu bytes\n", __func__, bytes);
459 		return NULL;
460 	}
461 
462 	return tlb;
463 }
464 
465 /*
466  * Statically reserve bounce buffer space and initialize bounce buffer data
467  * structures for the software IO TLB used to implement the DMA API.
468  */
469 void __init swiotlb_init_remap(bool addressing_limit, unsigned int flags,
470 		int (*remap)(void *tlb, unsigned long nslabs))
471 {
472 	struct io_tlb_pool *mem = &io_tlb_default_mem.defpool;
473 	unsigned long nslabs;
474 	unsigned int nareas;
475 	size_t alloc_size;
476 	void *tlb;
477 
478 	if (!addressing_limit && !swiotlb_force_bounce)
479 		return;
480 	if (swiotlb_force_disable)
481 		return;
482 
483 	io_tlb_default_mem.force_bounce = swiotlb_force_bounce;
484 
485 #ifdef CONFIG_SWIOTLB_DYNAMIC
486 	if (!remap)
487 		io_tlb_default_mem.can_grow = true;
488 	if (flags & SWIOTLB_ANY)
489 		io_tlb_default_mem.phys_limit = virt_to_phys(high_memory - 1);
490 	else
491 		io_tlb_default_mem.phys_limit = ARCH_LOW_ADDRESS_LIMIT;
492 #endif
493 
494 	if (!default_nareas)
495 		swiotlb_adjust_nareas(num_possible_cpus());
496 
497 	nslabs = default_nslabs;
498 	nareas = limit_nareas(default_nareas, nslabs);
499 	while ((tlb = swiotlb_memblock_alloc(nslabs, flags, remap)) == NULL) {
500 		if (nslabs <= IO_TLB_MIN_SLABS)
501 			return;
502 		nslabs = ALIGN(nslabs >> 1, IO_TLB_SEGSIZE);
503 		nareas = limit_nareas(nareas, nslabs);
504 	}
505 
506 	if (default_nslabs != nslabs) {
507 		pr_info("SWIOTLB bounce buffer size adjusted %lu -> %lu slabs",
508 			default_nslabs, nslabs);
509 		default_nslabs = nslabs;
510 	}
511 
512 	alloc_size = PAGE_ALIGN(array_size(sizeof(*mem->slots), nslabs));
513 	mem->slots = memblock_alloc(alloc_size, PAGE_SIZE);
514 	if (!mem->slots) {
515 		pr_warn("%s: Failed to allocate %zu bytes align=0x%lx\n",
516 			__func__, alloc_size, PAGE_SIZE);
517 		return;
518 	}
519 
520 	mem->areas = memblock_alloc(array_size(sizeof(struct io_tlb_area),
521 		nareas), SMP_CACHE_BYTES);
522 	if (!mem->areas) {
523 		pr_warn("%s: Failed to allocate mem->areas.\n", __func__);
524 		return;
525 	}
526 
527 	swiotlb_init_io_tlb_pool(mem, __pa(tlb), tlb, nslabs, false, nareas);
528 	add_mem_pool(&io_tlb_default_mem, mem);
529 
530 	if (flags & SWIOTLB_VERBOSE)
531 		swiotlb_print_info();
532 }
533 
534 void __init swiotlb_init(bool addressing_limit, unsigned int flags)
535 {
536 	swiotlb_init_remap(addressing_limit, flags, NULL);
537 }
538 
539 /*
540  * Systems with larger DMA zones (those that don't support ISA) can
541  * initialize the swiotlb later using the slab allocator if needed.
542  * This should be just like above, but with some error catching.
543  */
544 int swiotlb_init_late(size_t size, gfp_t gfp_mask,
545 		int (*remap)(void *tlb, unsigned long nslabs))
546 {
547 	struct io_tlb_pool *mem = &io_tlb_default_mem.defpool;
548 	unsigned long nslabs = ALIGN(size >> IO_TLB_SHIFT, IO_TLB_SEGSIZE);
549 	unsigned int order, area_order, slot_order;
550 	bool leak_pages = false;
551 	unsigned int nareas;
552 	unsigned char *vstart = NULL;
553 	bool retried = false;
554 	int rc = 0;
555 
556 	if (io_tlb_default_mem.nslabs)
557 		return 0;
558 
559 	if (swiotlb_force_disable)
560 		return 0;
561 
562 	io_tlb_default_mem.force_bounce = swiotlb_force_bounce;
563 
564 #ifdef CONFIG_SWIOTLB_DYNAMIC
565 	if (!remap)
566 		io_tlb_default_mem.can_grow = true;
567 	if (IS_ENABLED(CONFIG_ZONE_DMA) && (gfp_mask & __GFP_DMA))
568 		io_tlb_default_mem.phys_limit = zone_dma_limit;
569 	else if (IS_ENABLED(CONFIG_ZONE_DMA32) && (gfp_mask & __GFP_DMA32))
570 		io_tlb_default_mem.phys_limit = max(DMA_BIT_MASK(32), zone_dma_limit);
571 	else
572 		io_tlb_default_mem.phys_limit = virt_to_phys(high_memory - 1);
573 #endif
574 
575 	if (!default_nareas)
576 		swiotlb_adjust_nareas(num_possible_cpus());
577 
578 retry:
579 	order = get_order(nslabs << IO_TLB_SHIFT);
580 	nslabs = SLABS_PER_PAGE << order;
581 
582 	while ((SLABS_PER_PAGE << order) > IO_TLB_MIN_SLABS) {
583 		vstart = (void *)__get_free_pages(gfp_mask | __GFP_NOWARN,
584 						  order);
585 		if (vstart)
586 			break;
587 		order--;
588 		nslabs = SLABS_PER_PAGE << order;
589 		retried = true;
590 	}
591 
592 	if (!vstart)
593 		return -ENOMEM;
594 
595 	if (remap)
596 		rc = remap(vstart, nslabs);
597 	if (rc) {
598 		free_pages((unsigned long)vstart, order);
599 
600 		nslabs = ALIGN(nslabs >> 1, IO_TLB_SEGSIZE);
601 		if (nslabs < IO_TLB_MIN_SLABS)
602 			return rc;
603 		retried = true;
604 		goto retry;
605 	}
606 
607 	if (retried) {
608 		pr_warn("only able to allocate %ld MB\n",
609 			(PAGE_SIZE << order) >> 20);
610 	}
611 
612 	rc = -ENOMEM;
613 	nareas = limit_nareas(default_nareas, nslabs);
614 	area_order = get_order(array_size(sizeof(*mem->areas), nareas));
615 	mem->areas = (struct io_tlb_area *)
616 		__get_free_pages(GFP_KERNEL | __GFP_ZERO, area_order);
617 	if (!mem->areas)
618 		goto error_area;
619 
620 	slot_order = get_order(array_size(sizeof(*mem->slots), nslabs));
621 	mem->slots = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
622 					      slot_order);
623 	if (!mem->slots)
624 		goto error_slots;
625 
626 	if (io_tlb_default_mem.cc_shared) {
627 		rc = set_memory_decrypted((unsigned long)vstart,
628 					  (nslabs << IO_TLB_SHIFT) >> PAGE_SHIFT);
629 		if (rc) {
630 			leak_pages = true;
631 			goto error_decrypt;
632 		}
633 	}
634 
635 	swiotlb_init_io_tlb_pool(mem, virt_to_phys(vstart), vstart, nslabs, true,
636 				 nareas);
637 	add_mem_pool(&io_tlb_default_mem, mem);
638 
639 	swiotlb_print_info();
640 	return 0;
641 
642 error_decrypt:
643 	free_pages((unsigned long)mem->slots, slot_order);
644 error_slots:
645 	free_pages((unsigned long)mem->areas, area_order);
646 error_area:
647 	if (!leak_pages)
648 		free_pages((unsigned long)vstart, order);
649 	return rc;
650 }
651 
652 void __init swiotlb_exit(void)
653 {
654 	struct io_tlb_pool *mem = &io_tlb_default_mem.defpool;
655 	bool leak_pages = false;
656 	unsigned long tbl_vaddr;
657 	size_t tbl_size, slots_size;
658 	unsigned int area_order;
659 
660 	if (swiotlb_force_bounce)
661 		return;
662 
663 	if (!mem->nslabs)
664 		return;
665 
666 	pr_info("tearing down default memory pool\n");
667 	tbl_vaddr = (unsigned long)phys_to_virt(mem->start);
668 	tbl_size = PAGE_ALIGN(mem->end - mem->start);
669 	slots_size = PAGE_ALIGN(array_size(sizeof(*mem->slots), mem->nslabs));
670 
671 	if (io_tlb_default_mem.cc_shared) {
672 		if (set_memory_encrypted(tbl_vaddr, tbl_size >> PAGE_SHIFT))
673 			leak_pages = true;
674 	}
675 
676 	if (mem->late_alloc) {
677 		area_order = get_order(array_size(sizeof(*mem->areas),
678 			mem->nareas));
679 		free_pages((unsigned long)mem->areas, area_order);
680 		if (!leak_pages)
681 			free_pages(tbl_vaddr, get_order(tbl_size));
682 		free_pages((unsigned long)mem->slots, get_order(slots_size));
683 	} else {
684 		memblock_free(mem->areas,
685 			array_size(sizeof(*mem->areas), mem->nareas));
686 		if (!leak_pages)
687 			memblock_phys_free(mem->start, tbl_size);
688 		memblock_free(mem->slots, slots_size);
689 	}
690 
691 	memset(mem, 0, sizeof(*mem));
692 }
693 
694 #ifdef CONFIG_SWIOTLB_DYNAMIC
695 
696 /**
697  * alloc_dma_pages() - allocate pages to be used for DMA
698  * @gfp:	GFP flags for the allocation.
699  * @bytes:	Size of the buffer.
700  * @phys_limit:	Maximum allowed physical address of the buffer.
701  * @attrs:	DMA attributes for the allocation.
702  *
703  * Allocate pages from the buddy allocator. If successful, make the allocated
704  * pages decrypted that they can be used for DMA.
705  *
706  * Return: Decrypted pages, %NULL on allocation failure, or ERR_PTR(-EAGAIN)
707  * if the allocated physical address was above @phys_limit.
708  */
709 static struct page *alloc_dma_pages(gfp_t gfp, size_t bytes,
710 		u64 phys_limit, unsigned long attrs)
711 {
712 	unsigned int order = get_order(bytes);
713 	bool cc_shared = attrs & __DMA_ATTR_ALLOC_CC_SHARED;
714 	struct page *page;
715 	phys_addr_t paddr;
716 	void *vaddr;
717 
718 	page = alloc_pages(gfp, order);
719 	if (!page)
720 		return NULL;
721 
722 	paddr = page_to_phys(page);
723 	if (paddr + bytes - 1 > phys_limit) {
724 		__free_pages(page, order);
725 		return ERR_PTR(-EAGAIN);
726 	}
727 
728 	vaddr = phys_to_virt(paddr);
729 	if (cc_shared && set_memory_decrypted((unsigned long)vaddr, PFN_UP(bytes)))
730 		goto error;
731 	return page;
732 
733 error:
734 	/* Intentional leak if pages cannot be encrypted again. */
735 	if (cc_shared && !set_memory_encrypted((unsigned long)vaddr, PFN_UP(bytes)))
736 		__free_pages(page, order);
737 	return NULL;
738 }
739 
740 /**
741  * swiotlb_alloc_tlb() - allocate a dynamic IO TLB buffer
742  * @dev:	Device for which a memory pool is allocated.
743  * @mem:	SWIOTLB allocator for the pool.
744  * @bytes:	Size of the buffer.
745  * @phys_limit:	Maximum allowed physical address of the buffer.
746  * @gfp:	GFP flags for the allocation.
747  * @vaddr:	Receives the virtual address for the allocated buffer.
748  *
749  * Return: Allocated pages, or %NULL on allocation failure.
750  */
751 static struct page *swiotlb_alloc_tlb(struct device *dev,
752 		struct io_tlb_mem *mem, size_t bytes,
753 		u64 phys_limit, gfp_t gfp, void **vaddr)
754 {
755 	struct page *page;
756 	unsigned long attrs = mem->cc_shared ? __DMA_ATTR_ALLOC_CC_SHARED : 0;
757 
758 	*vaddr = NULL;
759 	/*
760 	 * Allocate from the atomic pools if memory is encrypted and
761 	 * the allocation is atomic, because decrypting may block.
762 	 */
763 	if (!gfpflags_allow_blocking(gfp) && dev && mem->cc_shared) {
764 
765 		if (!IS_ENABLED(CONFIG_DMA_COHERENT_POOL))
766 			return NULL;
767 
768 		return dma_alloc_from_pool(dev, bytes, vaddr, gfp,
769 					   attrs, dma_coherent_ok);
770 	}
771 
772 	gfp &= ~GFP_ZONEMASK;
773 	if (phys_limit <= zone_dma_limit)
774 		gfp |= __GFP_DMA;
775 	else if (phys_limit <= DMA_BIT_MASK(32))
776 		gfp |= __GFP_DMA32;
777 
778 	while (IS_ERR(page = alloc_dma_pages(gfp, bytes, phys_limit, attrs))) {
779 		if (IS_ENABLED(CONFIG_ZONE_DMA32) &&
780 		    phys_limit < DMA_BIT_MASK(64) &&
781 		    !(gfp & (__GFP_DMA32 | __GFP_DMA)))
782 			gfp |= __GFP_DMA32;
783 		else if (IS_ENABLED(CONFIG_ZONE_DMA) &&
784 			 !(gfp & __GFP_DMA))
785 			gfp = (gfp & ~__GFP_DMA32) | __GFP_DMA;
786 		else
787 			return NULL;
788 	}
789 
790 	if (page)
791 		*vaddr = phys_to_virt(page_to_phys(page));
792 	return page;
793 }
794 
795 /**
796  * swiotlb_free_tlb() - free a dynamically allocated IO TLB buffer
797  * @vaddr:	Virtual address of the buffer.
798  * @bytes:	Size of the buffer.
799  * @cc_shared: true if @vaddr was allocated decrypted and must be
800  *	re-encrypted before being freed
801  */
802 static void swiotlb_free_tlb(void *vaddr, size_t bytes, bool cc_shared)
803 {
804 	if (IS_ENABLED(CONFIG_DMA_COHERENT_POOL) &&
805 	    dma_free_from_pool(NULL, vaddr, bytes))
806 		return;
807 
808 	/* Intentional leak if pages cannot be encrypted again. */
809 	if (!cc_shared ||
810 	    !set_memory_encrypted((unsigned long)vaddr, PFN_UP(bytes)))
811 		__free_pages(virt_to_page(vaddr), get_order(bytes));
812 }
813 
814 /**
815  * swiotlb_alloc_pool() - allocate a new IO TLB memory pool
816  * @dev:	Device for which a memory pool is allocated.
817  * @mem:	SWIOTLB allocator for the pool.
818  * @minslabs:	Minimum number of slabs.
819  * @nslabs:	Desired (maximum) number of slabs.
820  * @nareas:	Number of areas.
821  * @phys_limit:	Maximum DMA buffer physical address.
822  * @gfp:	GFP flags for the allocations.
823  *
824  * Allocate and initialize a new IO TLB memory pool. The actual number of
825  * slabs may be reduced if allocation of @nslabs fails. If even
826  * @minslabs cannot be allocated, this function fails.
827  *
828  * Return: New memory pool, or %NULL on allocation failure.
829  */
830 static struct io_tlb_pool *swiotlb_alloc_pool(struct device *dev,
831 		struct io_tlb_mem *mem, unsigned long minslabs,
832 		unsigned long nslabs, unsigned int nareas, u64 phys_limit,
833 		gfp_t gfp)
834 {
835 	struct io_tlb_pool *pool;
836 	unsigned int slot_order;
837 	void *tlb_vaddr;
838 	struct page *tlb;
839 	size_t pool_size;
840 	size_t tlb_size;
841 
842 	if (nslabs > SLABS_PER_PAGE << MAX_PAGE_ORDER) {
843 		nslabs = SLABS_PER_PAGE << MAX_PAGE_ORDER;
844 		nareas = limit_nareas(nareas, nslabs);
845 	}
846 
847 	pool_size = sizeof(*pool) + array_size(sizeof(*pool->areas), nareas);
848 	pool = kzalloc(pool_size, gfp);
849 	if (!pool)
850 		goto error;
851 	pool->areas = (void *)pool + sizeof(*pool);
852 	pool->cc_shared = mem->cc_shared;
853 
854 	tlb_size = nslabs << IO_TLB_SHIFT;
855 	while (!(tlb = swiotlb_alloc_tlb(dev, mem, tlb_size,
856 					 phys_limit, gfp, &tlb_vaddr))) {
857 		if (nslabs <= minslabs)
858 			goto error_tlb;
859 		nslabs = ALIGN(nslabs >> 1, IO_TLB_SEGSIZE);
860 		nareas = limit_nareas(nareas, nslabs);
861 		tlb_size = nslabs << IO_TLB_SHIFT;
862 	}
863 
864 	slot_order = get_order(array_size(sizeof(*pool->slots), nslabs));
865 	pool->slots = (struct io_tlb_slot *)
866 		__get_free_pages(gfp, slot_order);
867 	if (!pool->slots)
868 		goto error_slots;
869 
870 	swiotlb_init_io_tlb_pool(pool, page_to_phys(tlb), tlb_vaddr, nslabs,
871 				 true, nareas);
872 	return pool;
873 
874 error_slots:
875 	swiotlb_free_tlb(tlb_vaddr, tlb_size, mem->cc_shared);
876 error_tlb:
877 	kfree(pool);
878 error:
879 	return NULL;
880 }
881 
882 /**
883  * swiotlb_dyn_alloc() - dynamic memory pool allocation worker
884  * @work:	Pointer to dyn_alloc in struct io_tlb_mem.
885  */
886 static void swiotlb_dyn_alloc(struct work_struct *work)
887 {
888 	struct io_tlb_mem *mem =
889 		container_of(work, struct io_tlb_mem, dyn_alloc);
890 	struct io_tlb_pool *pool;
891 
892 	pool = swiotlb_alloc_pool(NULL, mem, IO_TLB_MIN_SLABS, default_nslabs,
893 				  default_nareas, mem->phys_limit, GFP_KERNEL);
894 	if (!pool) {
895 		pr_warn_ratelimited("Failed to allocate new pool");
896 		return;
897 	}
898 
899 	add_mem_pool(mem, pool);
900 }
901 
902 static void swiotlb_dyn_free_work(struct work_struct *work)
903 {
904 	struct io_tlb_pool *pool =
905 		container_of(to_rcu_work(work), struct io_tlb_pool, dyn_free);
906 	size_t slots_size = array_size(sizeof(*pool->slots), pool->nslabs);
907 	size_t tlb_size = pool->end - pool->start;
908 
909 	free_pages((unsigned long)pool->slots, get_order(slots_size));
910 	swiotlb_free_tlb(pool->vaddr, tlb_size, pool->cc_shared);
911 	kfree(pool);
912 }
913 
914 static void swiotlb_schedule_dyn_free(struct io_tlb_pool *pool)
915 {
916 	INIT_RCU_WORK(&pool->dyn_free, swiotlb_dyn_free_work);
917 	queue_rcu_work(system_wq, &pool->dyn_free);
918 }
919 
920 /**
921  * __swiotlb_find_pool() - find the IO TLB pool for a physical address
922  * @dev:        Device which has mapped the DMA buffer.
923  * @paddr:      Physical address within the DMA buffer.
924  *
925  * Find the IO TLB memory pool descriptor which contains the given physical
926  * address, if any. This function is for use only when the dev is known to
927  * be using swiotlb. Use swiotlb_find_pool() for the more general case
928  * when this condition is not met.
929  *
930  * Return: Memory pool which contains @paddr, or %NULL if none.
931  */
932 struct io_tlb_pool *__swiotlb_find_pool(struct device *dev, phys_addr_t paddr)
933 {
934 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
935 	struct io_tlb_pool *pool;
936 
937 	rcu_read_lock();
938 	list_for_each_entry_rcu(pool, &mem->pools, node) {
939 		if (paddr >= pool->start && paddr < pool->end)
940 			goto out;
941 	}
942 
943 	list_for_each_entry_rcu(pool, &dev->dma_io_tlb_pools, node) {
944 		if (paddr >= pool->start && paddr < pool->end)
945 			goto out;
946 	}
947 	pool = NULL;
948 out:
949 	rcu_read_unlock();
950 	return pool;
951 }
952 
953 /**
954  * swiotlb_del_pool() - remove an IO TLB pool from a device
955  * @dev:	Owning device.
956  * @pool:	Memory pool to be removed.
957  */
958 static void swiotlb_del_pool(struct device *dev, struct io_tlb_pool *pool)
959 {
960 	unsigned long flags;
961 
962 	spin_lock_irqsave(&dev->dma_io_tlb_lock, flags);
963 	list_del_rcu(&pool->node);
964 	spin_unlock_irqrestore(&dev->dma_io_tlb_lock, flags);
965 
966 	swiotlb_schedule_dyn_free(pool);
967 }
968 
969 #endif	/* CONFIG_SWIOTLB_DYNAMIC */
970 
971 /**
972  * swiotlb_dev_init() - initialize swiotlb fields in &struct device
973  * @dev:	Device to be initialized.
974  */
975 void swiotlb_dev_init(struct device *dev)
976 {
977 	dev->dma_io_tlb_mem = &io_tlb_default_mem;
978 #ifdef CONFIG_SWIOTLB_DYNAMIC
979 	INIT_LIST_HEAD(&dev->dma_io_tlb_pools);
980 	spin_lock_init(&dev->dma_io_tlb_lock);
981 	dev->dma_uses_io_tlb = false;
982 #endif
983 }
984 
985 /**
986  * swiotlb_align_offset() - Get required offset into an IO TLB allocation.
987  * @dev:         Owning device.
988  * @align_mask:  Allocation alignment mask.
989  * @addr:        DMA address.
990  *
991  * Return the minimum offset from the start of an IO TLB allocation which is
992  * required for a given buffer address and allocation alignment to keep the
993  * device happy.
994  *
995  * First, the address bits covered by min_align_mask must be identical in the
996  * original address and the bounce buffer address. High bits are preserved by
997  * choosing a suitable IO TLB slot, but bits below IO_TLB_SHIFT require extra
998  * padding bytes before the bounce buffer.
999  *
1000  * Second, @align_mask specifies which bits of the first allocated slot must
1001  * be zero. This may require allocating additional padding slots, and then the
1002  * offset (in bytes) from the first such padding slot is returned.
1003  */
1004 static unsigned int swiotlb_align_offset(struct device *dev,
1005 					 unsigned int align_mask, u64 addr)
1006 {
1007 	return addr & dma_get_min_align_mask(dev) &
1008 		(align_mask | (IO_TLB_SIZE - 1));
1009 }
1010 
1011 /*
1012  * Bounce: copy the swiotlb buffer from or back to the original dma location
1013  */
1014 static void swiotlb_bounce(struct device *dev, phys_addr_t tlb_addr, size_t size,
1015 			   enum dma_data_direction dir, struct io_tlb_pool *mem)
1016 {
1017 	int index = (tlb_addr - mem->start) >> IO_TLB_SHIFT;
1018 	phys_addr_t orig_addr = mem->slots[index].orig_addr;
1019 	size_t alloc_size = mem->slots[index].alloc_size;
1020 	unsigned char *vaddr = mem->vaddr + tlb_addr - mem->start;
1021 	int tlb_offset;
1022 
1023 	if (orig_addr == INVALID_PHYS_ADDR)
1024 		return;
1025 
1026 	if (dir == DMA_FROM_DEVICE && !dev_is_dma_coherent(dev))
1027 		arch_sync_dma_flush();
1028 
1029 	/*
1030 	 * It's valid for tlb_offset to be negative. This can happen when the
1031 	 * "offset" returned by swiotlb_align_offset() is non-zero, and the
1032 	 * tlb_addr is pointing within the first "offset" bytes of the second
1033 	 * or subsequent slots of the allocated swiotlb area. While it's not
1034 	 * valid for tlb_addr to be pointing within the first "offset" bytes
1035 	 * of the first slot, there's no way to check for such an error since
1036 	 * this function can't distinguish the first slot from the second and
1037 	 * subsequent slots.
1038 	 */
1039 	tlb_offset = (tlb_addr & (IO_TLB_SIZE - 1)) -
1040 		     swiotlb_align_offset(dev, 0, orig_addr);
1041 
1042 	orig_addr += tlb_offset;
1043 	alloc_size -= tlb_offset;
1044 
1045 	if (size > alloc_size) {
1046 		dev_WARN_ONCE(dev, 1,
1047 			"Buffer overflow detected. Allocation size: %zu. Mapping size: %zu.\n",
1048 			alloc_size, size);
1049 		size = alloc_size;
1050 	}
1051 
1052 	if (PhysHighMem(orig_addr)) {
1053 		unsigned long pfn = PFN_DOWN(orig_addr);
1054 		unsigned int offset = orig_addr & ~PAGE_MASK;
1055 		struct page *page;
1056 		unsigned int sz = 0;
1057 		unsigned long flags;
1058 
1059 		while (size) {
1060 			sz = min_t(size_t, PAGE_SIZE - offset, size);
1061 
1062 			local_irq_save(flags);
1063 			page = pfn_to_page(pfn);
1064 			if (dir == DMA_TO_DEVICE) {
1065 				/*
1066 				 * Ideally, kmsan_check_highmem_page()
1067 				 * could be used here to detect infoleaks,
1068 				 * but callers may map uninitialized buffers
1069 				 * that will be written by the device,
1070 				 * causing false positives.
1071 				 */
1072 				memcpy_from_page(vaddr, page, offset, sz);
1073 			} else {
1074 				kmsan_unpoison_memory(vaddr, sz);
1075 				memcpy_to_page(page, offset, vaddr, sz);
1076 			}
1077 			local_irq_restore(flags);
1078 
1079 			size -= sz;
1080 			pfn++;
1081 			vaddr += sz;
1082 			offset = 0;
1083 		}
1084 	} else if (dir == DMA_TO_DEVICE) {
1085 		/*
1086 		 * Ideally, kmsan_check_memory() could be used here to detect
1087 		 * infoleaks (uninitialized data being sent to device), but
1088 		 * callers may map uninitialized buffers that will be written
1089 		 * by the device, causing false positives.
1090 		 */
1091 		memcpy(vaddr, phys_to_virt(orig_addr), size);
1092 	} else {
1093 		kmsan_unpoison_memory(vaddr, size);
1094 		memcpy(phys_to_virt(orig_addr), vaddr, size);
1095 	}
1096 }
1097 
1098 static inline phys_addr_t slot_addr(phys_addr_t start, phys_addr_t idx)
1099 {
1100 	return start + (idx << IO_TLB_SHIFT);
1101 }
1102 
1103 /*
1104  * Carefully handle integer overflow which can occur when boundary_mask == ~0UL.
1105  */
1106 static inline unsigned long get_max_slots(unsigned long boundary_mask)
1107 {
1108 	return (boundary_mask >> IO_TLB_SHIFT) + 1;
1109 }
1110 
1111 static unsigned int wrap_area_index(struct io_tlb_pool *mem, unsigned int index)
1112 {
1113 	if (index >= mem->area_nslabs)
1114 		return 0;
1115 	return index;
1116 }
1117 
1118 #ifdef CONFIG_SWIOTLB_DYNAMIC
1119 #ifdef CONFIG_DEBUG_FS
1120 static void inc_transient_used(struct io_tlb_mem *mem, unsigned int nslots)
1121 {
1122 	atomic_long_add(nslots, &mem->transient_nslabs);
1123 }
1124 
1125 static void dec_transient_used(struct io_tlb_mem *mem, unsigned int nslots)
1126 {
1127 	atomic_long_sub(nslots, &mem->transient_nslabs);
1128 }
1129 
1130 #else /* !CONFIG_DEBUG_FS */
1131 static void inc_transient_used(struct io_tlb_mem *mem, unsigned int nslots)
1132 {
1133 }
1134 static void dec_transient_used(struct io_tlb_mem *mem, unsigned int nslots)
1135 {
1136 }
1137 #endif /* CONFIG_DEBUG_FS */
1138 #endif /* CONFIG_SWIOTLB_DYNAMIC */
1139 
1140 /**
1141  * swiotlb_search_pool_area() - search one memory area in one pool
1142  * @dev:	Device which maps the buffer.
1143  * @pool:	Memory pool to be searched.
1144  * @area_index:	Index of the IO TLB memory area to be searched.
1145  * @orig_addr:	Original (non-bounced) IO buffer address.
1146  * @tbl_dma_addr: DMA address of the bounce buffer.
1147  * @alloc_size: Total requested size of the bounce buffer,
1148  *		including initial alignment padding.
1149  * @alloc_align_mask:	Required alignment of the allocated buffer.
1150  *
1151  * Find a suitable sequence of IO TLB entries for the request and allocate
1152  * a buffer from the given IO TLB memory area.
1153  * This function takes care of locking.
1154  *
1155  * Return: Index of the first allocated slot, or -1 on error.
1156  */
1157 static int swiotlb_search_pool_area(struct device *dev, struct io_tlb_pool *pool,
1158 		int area_index, phys_addr_t orig_addr, dma_addr_t tbl_dma_addr,
1159 		size_t alloc_size, unsigned int alloc_align_mask)
1160 {
1161 	struct io_tlb_area *area = pool->areas + area_index;
1162 	unsigned long boundary_mask = dma_get_seg_boundary(dev);
1163 	unsigned long max_slots = get_max_slots(boundary_mask);
1164 	unsigned int iotlb_align_mask = dma_get_min_align_mask(dev);
1165 	unsigned int nslots = nr_slots(alloc_size), stride;
1166 	unsigned int offset = swiotlb_align_offset(dev, 0, orig_addr);
1167 	unsigned int index, slots_checked, count = 0, i;
1168 	unsigned long flags;
1169 	unsigned int slot_base;
1170 	unsigned int slot_index;
1171 
1172 	BUG_ON(!nslots);
1173 	BUG_ON(area_index >= pool->nareas);
1174 
1175 	tbl_dma_addr &= boundary_mask;
1176 
1177 	/*
1178 	 * Historically, swiotlb allocations >= PAGE_SIZE were guaranteed to be
1179 	 * page-aligned in the absence of any other alignment requirements.
1180 	 * 'alloc_align_mask' was later introduced to specify the alignment
1181 	 * explicitly, however this is passed as zero for streaming mappings
1182 	 * and so we preserve the old behaviour there in case any drivers are
1183 	 * relying on it.
1184 	 */
1185 	if (!alloc_align_mask && !iotlb_align_mask && alloc_size >= PAGE_SIZE)
1186 		alloc_align_mask = PAGE_SIZE - 1;
1187 
1188 	/*
1189 	 * Ensure that the allocation is at least slot-aligned and update
1190 	 * 'iotlb_align_mask' to ignore bits that will be preserved when
1191 	 * offsetting into the allocation.
1192 	 */
1193 	alloc_align_mask |= (IO_TLB_SIZE - 1);
1194 	iotlb_align_mask &= ~alloc_align_mask;
1195 
1196 	/*
1197 	 * For mappings with an alignment requirement don't bother looping to
1198 	 * unaligned slots once we found an aligned one.
1199 	 */
1200 	stride = get_max_slots(max(alloc_align_mask, iotlb_align_mask));
1201 
1202 	spin_lock_irqsave(&area->lock, flags);
1203 	if (unlikely(nslots > pool->area_nslabs - area->used))
1204 		goto not_found;
1205 
1206 	slot_base = area_index * pool->area_nslabs;
1207 	index = area->index;
1208 
1209 	for (slots_checked = 0; slots_checked < pool->area_nslabs; ) {
1210 		phys_addr_t tlb_addr;
1211 
1212 		slot_index = slot_base + index;
1213 		tlb_addr = slot_addr(tbl_dma_addr, slot_index);
1214 
1215 		if ((tlb_addr & alloc_align_mask) ||
1216 		    (orig_addr && (tlb_addr & iotlb_align_mask) !=
1217 				  (orig_addr & iotlb_align_mask))) {
1218 			index = wrap_area_index(pool, index + 1);
1219 			slots_checked++;
1220 			continue;
1221 		}
1222 
1223 		if (!iommu_is_span_boundary(slot_index, nslots,
1224 					    nr_slots(tbl_dma_addr),
1225 					    max_slots)) {
1226 			if (pool->slots[slot_index].list >= nslots)
1227 				goto found;
1228 		}
1229 		index = wrap_area_index(pool, index + stride);
1230 		slots_checked += stride;
1231 	}
1232 
1233 not_found:
1234 	spin_unlock_irqrestore(&area->lock, flags);
1235 	return -1;
1236 
1237 found:
1238 	/*
1239 	 * If we find a slot that indicates we have 'nslots' number of
1240 	 * contiguous buffers, we allocate the buffers from that slot onwards
1241 	 * and set the list of free entries to '0' indicating unavailable.
1242 	 */
1243 	for (i = slot_index; i < slot_index + nslots; i++) {
1244 		pool->slots[i].list = 0;
1245 		pool->slots[i].alloc_size = alloc_size - (offset +
1246 				((i - slot_index) << IO_TLB_SHIFT));
1247 	}
1248 	for (i = slot_index - 1;
1249 	     io_tlb_offset(i) != IO_TLB_SEGSIZE - 1 &&
1250 	     pool->slots[i].list; i--)
1251 		pool->slots[i].list = ++count;
1252 
1253 	/*
1254 	 * Update the indices to avoid searching in the next round.
1255 	 */
1256 	area->index = wrap_area_index(pool, index + nslots);
1257 	area->used += nslots;
1258 	spin_unlock_irqrestore(&area->lock, flags);
1259 
1260 	inc_used_and_hiwater(dev->dma_io_tlb_mem, nslots);
1261 	return slot_index;
1262 }
1263 
1264 #ifdef CONFIG_SWIOTLB_DYNAMIC
1265 
1266 /**
1267  * swiotlb_search_area() - search one memory area in all pools
1268  * @dev:	Device which maps the buffer.
1269  * @start_cpu:	Start CPU number.
1270  * @cpu_offset:	Offset from @start_cpu.
1271  * @orig_addr:	Original (non-bounced) IO buffer address.
1272  * @alloc_size: Total requested size of the bounce buffer,
1273  *		including initial alignment padding.
1274  * @alloc_align_mask:	Required alignment of the allocated buffer.
1275  * @retpool:	Used memory pool, updated on return.
1276  *
1277  * Search one memory area in all pools for a sequence of slots that match the
1278  * allocation constraints.
1279  *
1280  * Return: Index of the first allocated slot, or -1 on error.
1281  */
1282 static int swiotlb_search_area(struct device *dev, int start_cpu,
1283 		int cpu_offset, phys_addr_t orig_addr, size_t alloc_size,
1284 		unsigned int alloc_align_mask, struct io_tlb_pool **retpool)
1285 {
1286 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
1287 	struct io_tlb_pool *pool;
1288 	dma_addr_t tbl_dma_addr;
1289 	int area_index;
1290 	int index = -1;
1291 
1292 	rcu_read_lock();
1293 	list_for_each_entry_rcu(pool, &mem->pools, node) {
1294 		if (cpu_offset >= pool->nareas)
1295 			continue;
1296 		area_index = (start_cpu + cpu_offset) & (pool->nareas - 1);
1297 
1298 		if (mem->cc_shared)
1299 			tbl_dma_addr = phys_to_dma_unencrypted(dev, pool->start);
1300 		else
1301 			tbl_dma_addr = phys_to_dma_encrypted(dev, pool->start);
1302 
1303 		index = swiotlb_search_pool_area(dev, pool, area_index,
1304 						 orig_addr, tbl_dma_addr,
1305 						 alloc_size, alloc_align_mask);
1306 		if (index >= 0) {
1307 			*retpool = pool;
1308 			break;
1309 		}
1310 	}
1311 	rcu_read_unlock();
1312 	return index;
1313 }
1314 
1315 /**
1316  * swiotlb_find_slots() - search for slots in the whole swiotlb
1317  * @dev:	Device which maps the buffer.
1318  * @orig_addr:	Original (non-bounced) IO buffer address.
1319  * @alloc_size: Total requested size of the bounce buffer,
1320  *		including initial alignment padding.
1321  * @alloc_align_mask:	Required alignment of the allocated buffer.
1322  * @retpool:	Used memory pool, updated on return.
1323  *
1324  * Search through the whole software IO TLB to find a sequence of slots that
1325  * match the allocation constraints.
1326  *
1327  * Return: Index of the first allocated slot, or -1 on error.
1328  */
1329 static int swiotlb_find_slots(struct device *dev, phys_addr_t orig_addr,
1330 		size_t alloc_size, unsigned int alloc_align_mask,
1331 		struct io_tlb_pool **retpool)
1332 {
1333 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
1334 	struct io_tlb_pool *pool;
1335 	dma_addr_t tbl_dma_addr;
1336 	unsigned long nslabs;
1337 	unsigned long flags;
1338 	u64 phys_limit;
1339 	int cpu, i;
1340 	int index;
1341 
1342 	if (alloc_size > IO_TLB_SEGSIZE * IO_TLB_SIZE)
1343 		return -1;
1344 
1345 	cpu = raw_smp_processor_id();
1346 	for (i = 0; i < default_nareas; ++i) {
1347 		index = swiotlb_search_area(dev, cpu, i, orig_addr, alloc_size,
1348 					    alloc_align_mask, &pool);
1349 		if (index >= 0)
1350 			goto found;
1351 	}
1352 
1353 	if (!mem->can_grow)
1354 		return -1;
1355 
1356 	schedule_work(&mem->dyn_alloc);
1357 
1358 	nslabs = nr_slots(alloc_size);
1359 	phys_limit = min_not_zero(*dev->dma_mask, dev->bus_dma_limit);
1360 	pool = swiotlb_alloc_pool(dev, mem, nslabs, nslabs, 1, phys_limit,
1361 				  GFP_NOWAIT);
1362 	if (!pool)
1363 		return -1;
1364 
1365 	if (mem->cc_shared)
1366 		tbl_dma_addr = phys_to_dma_unencrypted(dev, pool->start);
1367 	else
1368 		tbl_dma_addr = phys_to_dma_encrypted(dev, pool->start);
1369 
1370 	index = swiotlb_search_pool_area(dev, pool, 0, orig_addr, tbl_dma_addr,
1371 					 alloc_size, alloc_align_mask);
1372 	if (index < 0) {
1373 		swiotlb_schedule_dyn_free(pool);
1374 		return -1;
1375 	}
1376 
1377 	pool->transient = true;
1378 	spin_lock_irqsave(&dev->dma_io_tlb_lock, flags);
1379 	list_add_rcu(&pool->node, &dev->dma_io_tlb_pools);
1380 	spin_unlock_irqrestore(&dev->dma_io_tlb_lock, flags);
1381 	inc_transient_used(mem, pool->nslabs);
1382 
1383 found:
1384 	WRITE_ONCE(dev->dma_uses_io_tlb, true);
1385 
1386 	/*
1387 	 * The general barrier orders reads and writes against a presumed store
1388 	 * of the SWIOTLB buffer address by a device driver (to a driver private
1389 	 * data structure). It serves two purposes.
1390 	 *
1391 	 * First, the store to dev->dma_uses_io_tlb must be ordered before the
1392 	 * presumed store. This guarantees that the returned buffer address
1393 	 * cannot be passed to another CPU before updating dev->dma_uses_io_tlb.
1394 	 *
1395 	 * Second, the load from mem->pools must be ordered before the same
1396 	 * presumed store. This guarantees that the returned buffer address
1397 	 * cannot be observed by another CPU before an update of the RCU list
1398 	 * that was made by swiotlb_dyn_alloc() on a third CPU (cf. multicopy
1399 	 * atomicity).
1400 	 *
1401 	 * See also the comment in swiotlb_find_pool().
1402 	 */
1403 	smp_mb();
1404 
1405 	*retpool = pool;
1406 	return index;
1407 }
1408 
1409 #else  /* !CONFIG_SWIOTLB_DYNAMIC */
1410 
1411 static int swiotlb_find_slots(struct device *dev, phys_addr_t orig_addr,
1412 		size_t alloc_size, unsigned int alloc_align_mask,
1413 		struct io_tlb_pool **retpool)
1414 {
1415 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
1416 	struct io_tlb_pool *pool;
1417 	dma_addr_t tbl_dma_addr;
1418 	int start, i;
1419 	int index;
1420 
1421 	*retpool = pool = &mem->defpool;
1422 	if (mem->cc_shared)
1423 		tbl_dma_addr = phys_to_dma_unencrypted(dev, pool->start);
1424 	else
1425 		tbl_dma_addr = phys_to_dma_encrypted(dev, pool->start);
1426 
1427 	i = start = raw_smp_processor_id() & (pool->nareas - 1);
1428 	do {
1429 		index = swiotlb_search_pool_area(dev, pool, i, orig_addr,
1430 						 tbl_dma_addr, alloc_size,
1431 						 alloc_align_mask);
1432 		if (index >= 0)
1433 			return index;
1434 		if (++i >= pool->nareas)
1435 			i = 0;
1436 	} while (i != start);
1437 	return -1;
1438 }
1439 
1440 #endif /* CONFIG_SWIOTLB_DYNAMIC */
1441 
1442 /**
1443  * mem_pool_used() - get number of used slots in a memory pool
1444  * @pool:	Software IO TLB memory pool.
1445  *
1446  * The result is not accurate, see mem_used().
1447  *
1448  * Return: Approximate number of used slots.
1449  */
1450 static unsigned long mem_pool_used(struct io_tlb_pool *pool)
1451 {
1452 	int i;
1453 	unsigned long used = 0;
1454 
1455 	for (i = 0; i < pool->nareas; i++)
1456 		used += pool->areas[i].used;
1457 	return used;
1458 }
1459 
1460 /**
1461  * mem_used() - get number of used slots in an allocator
1462  * @mem:	Software IO TLB allocator.
1463  *
1464  * When trace_hiwater and CONFIG_DEBUG_FS is enabled, the result is accurate
1465  * because the total number of used slots is tracked in mem->total_used.
1466  * Otherwise, the result is an approximation, because there is no locking of
1467  * individual areas.
1468  *
1469  * Return: Number of used slots.
1470  */
1471 static unsigned long mem_used(struct io_tlb_mem *mem)
1472 {
1473 #ifdef CONFIG_DEBUG_FS
1474     if (track_hiwater_enabled)
1475 	    return atomic_long_read(&mem->total_used);
1476 #endif
1477 
1478 #ifdef CONFIG_SWIOTLB_DYNAMIC
1479 	struct io_tlb_pool *pool;
1480 	unsigned long used = 0;
1481 
1482 	rcu_read_lock();
1483 	list_for_each_entry_rcu(pool, &mem->pools, node)
1484 		used += mem_pool_used(pool);
1485 	rcu_read_unlock();
1486 
1487 	return used;
1488 #else
1489 	return mem_pool_used(&mem->defpool);
1490 #endif
1491 }
1492 
1493 /**
1494  * swiotlb_tbl_map_single() - bounce buffer map a single contiguous physical area
1495  * @dev:		Device which maps the buffer.
1496  * @orig_addr:		Original (non-bounced) physical IO buffer address
1497  * @mapping_size:	Requested size of the actual bounce buffer, excluding
1498  *			any pre- or post-padding for alignment
1499  * @alloc_align_mask:	Required start and end alignment of the allocated buffer
1500  * @dir:		DMA direction
1501  * @attrs:		Optional DMA attributes for the map operation, updated
1502  *			to match the selected SWIOTLB pool
1503  *
1504  * Find and allocate a suitable sequence of IO TLB slots for the request.
1505  * The device's SWIOTLB pool must match the device's current DMA encryption
1506  * requirements. If the device requires decrypted DMA, bouncing is done through
1507  * an unencrypted pool and the mapping is marked shared. If the device can DMA
1508  * to encrypted memory, bouncing is done through an encrypted pool even when the
1509  * original DMA address was unencrypted. Enabling encrypted DMA for a device is
1510  * therefore expected to update its default io_tlb_mem to an encrypted pool, so
1511  * later bounce mappings for both encrypted and decrypted original memory use
1512  * that encrypted pool.
1513  *
1514  * The allocated space starts at an alignment specified by alloc_align_mask,
1515  * and the size of the allocated space is rounded up so that the total amount
1516  * of allocated space is a multiple of (alloc_align_mask + 1). If
1517  * alloc_align_mask is zero, the allocated space may be at any alignment and
1518  * the size is not rounded up.
1519  *
1520  * The returned address is within the allocated space and matches the bits
1521  * of orig_addr that are specified in the DMA min_align_mask for the device. As
1522  * such, this returned address may be offset from the beginning of the allocated
1523  * space. The bounce buffer space starting at the returned address for
1524  * mapping_size bytes is initialized to the contents of the original IO buffer
1525  * area. Any pre-padding (due to an offset) and any post-padding (due to
1526  * rounding-up the size) is not initialized.
1527  */
1528 phys_addr_t swiotlb_tbl_map_single(struct device *dev, phys_addr_t orig_addr,
1529 		size_t mapping_size, unsigned int alloc_align_mask,
1530 		enum dma_data_direction dir, unsigned long *attrs)
1531 {
1532 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
1533 	unsigned int offset;
1534 	struct io_tlb_pool *pool;
1535 	unsigned int i;
1536 	size_t size;
1537 	int index;
1538 	phys_addr_t tlb_addr;
1539 	unsigned short pad_slots;
1540 
1541 	if (!mem || !mem->nslabs) {
1542 		dev_warn_ratelimited(dev,
1543 			"Can not allocate SWIOTLB buffer earlier and can't now provide you with the DMA bounce buffer");
1544 		return (phys_addr_t)DMA_MAPPING_ERROR;
1545 	}
1546 
1547 	if (cc_platform_has(CC_ATTR_MEM_ENCRYPT))
1548 		pr_warn_once("Memory encryption is active and system is using DMA bounce buffers\n");
1549 
1550 	if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) {
1551 
1552 		/* swiotlb pool is incorrect for this device */
1553 		if (unlikely(mem->cc_shared != force_dma_unencrypted(dev)))
1554 			return (phys_addr_t)DMA_MAPPING_ERROR;
1555 
1556 	} else if (cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT)) {
1557 		/*
1558 		 * On hosts with memory encryption, SWIOTLB-backed memory is
1559 		 * unencrypted. DMA addresses returned for bounce buffers must
1560 		 * therefore be marked unencrypted, even for devices that can
1561 		 * address encrypted memory. This also preserves swiotlb=force
1562 		 * behavior for those devices.
1563 		 */
1564 		if (unlikely(!mem->cc_shared))
1565 			return (phys_addr_t)DMA_MAPPING_ERROR;
1566 	}
1567 
1568 	/* Force attrs to match the kind of memory in the pool */
1569 	if (mem->cc_shared)
1570 		*attrs |= DMA_ATTR_CC_SHARED;
1571 	else
1572 		*attrs &= ~DMA_ATTR_CC_SHARED;
1573 
1574 	/*
1575 	 * The default swiotlb memory pool is allocated with PAGE_SIZE
1576 	 * alignment. If a mapping is requested with larger alignment,
1577 	 * the mapping may be unable to use the initial slot(s) in all
1578 	 * sets of IO_TLB_SEGSIZE slots. In such case, a mapping request
1579 	 * of or near the maximum mapping size would always fail.
1580 	 */
1581 	dev_WARN_ONCE(dev, alloc_align_mask > ~PAGE_MASK,
1582 		"Alloc alignment may prevent fulfilling requests with max mapping_size\n");
1583 
1584 	offset = swiotlb_align_offset(dev, alloc_align_mask, orig_addr);
1585 	size = ALIGN(mapping_size + offset, alloc_align_mask + 1);
1586 	index = swiotlb_find_slots(dev, orig_addr, size, alloc_align_mask, &pool);
1587 	if (index == -1) {
1588 		if (!(*attrs & DMA_ATTR_NO_WARN))
1589 			dev_warn_ratelimited(dev,
1590 	"swiotlb buffer is full (sz: %zd bytes), total %lu (slots), used %lu (slots)\n",
1591 				 size, mem->nslabs, mem_used(mem));
1592 		return (phys_addr_t)DMA_MAPPING_ERROR;
1593 	}
1594 
1595 	/*
1596 	 * If dma_skip_sync was set, reset it on first SWIOTLB buffer
1597 	 * mapping to always sync SWIOTLB buffers.
1598 	 */
1599 	dma_reset_need_sync(dev);
1600 
1601 	/*
1602 	 * Save away the mapping from the original address to the DMA address.
1603 	 * This is needed when we sync the memory.  Then we sync the buffer if
1604 	 * needed.
1605 	 */
1606 	pad_slots = offset >> IO_TLB_SHIFT;
1607 	offset &= (IO_TLB_SIZE - 1);
1608 	index += pad_slots;
1609 	pool->slots[index].pad_slots = pad_slots;
1610 	for (i = 0; i < (nr_slots(size) - pad_slots); i++)
1611 		pool->slots[index + i].orig_addr = slot_addr(orig_addr, i);
1612 	tlb_addr = slot_addr(pool->start, index) + offset;
1613 	/*
1614 	 * When the device is writing memory, i.e. dir == DMA_FROM_DEVICE, copy
1615 	 * the original buffer to the TLB buffer before initiating DMA in order
1616 	 * to preserve the original's data if the device does a partial write,
1617 	 * i.e. if the device doesn't overwrite the entire buffer.  Preserving
1618 	 * the original data, even if it's garbage, is necessary to match
1619 	 * hardware behavior.  Use of swiotlb is supposed to be transparent,
1620 	 * i.e. swiotlb must not corrupt memory by clobbering unwritten bytes.
1621 	 */
1622 	swiotlb_bounce(dev, tlb_addr, mapping_size, DMA_TO_DEVICE, pool);
1623 	return tlb_addr;
1624 }
1625 
1626 static void swiotlb_release_slots(struct device *dev, phys_addr_t tlb_addr,
1627 				  struct io_tlb_pool *mem)
1628 {
1629 	unsigned long flags;
1630 	unsigned int offset = swiotlb_align_offset(dev, 0, tlb_addr);
1631 	int index, nslots, aindex;
1632 	struct io_tlb_area *area;
1633 	int count, i;
1634 
1635 	index = (tlb_addr - offset - mem->start) >> IO_TLB_SHIFT;
1636 	index -= mem->slots[index].pad_slots;
1637 	nslots = nr_slots(mem->slots[index].alloc_size + offset);
1638 	aindex = index / mem->area_nslabs;
1639 	area = &mem->areas[aindex];
1640 
1641 	/*
1642 	 * Return the buffer to the free list by setting the corresponding
1643 	 * entries to indicate the number of contiguous entries available.
1644 	 * While returning the entries to the free list, we merge the entries
1645 	 * with slots below and above the pool being returned.
1646 	 */
1647 	BUG_ON(aindex >= mem->nareas);
1648 
1649 	spin_lock_irqsave(&area->lock, flags);
1650 	if (index + nslots < ALIGN(index + 1, IO_TLB_SEGSIZE))
1651 		count = mem->slots[index + nslots].list;
1652 	else
1653 		count = 0;
1654 
1655 	/*
1656 	 * Step 1: return the slots to the free list, merging the slots with
1657 	 * superceeding slots
1658 	 */
1659 	for (i = index + nslots - 1; i >= index; i--) {
1660 		mem->slots[i].list = ++count;
1661 		mem->slots[i].orig_addr = INVALID_PHYS_ADDR;
1662 		mem->slots[i].alloc_size = 0;
1663 		mem->slots[i].pad_slots = 0;
1664 	}
1665 
1666 	/*
1667 	 * Step 2: merge the returned slots with the preceding slots, if
1668 	 * available (non zero)
1669 	 */
1670 	for (i = index - 1;
1671 	     io_tlb_offset(i) != IO_TLB_SEGSIZE - 1 && mem->slots[i].list;
1672 	     i--)
1673 		mem->slots[i].list = ++count;
1674 	area->used -= nslots;
1675 	spin_unlock_irqrestore(&area->lock, flags);
1676 
1677 	dec_used(dev->dma_io_tlb_mem, nslots);
1678 }
1679 
1680 #ifdef CONFIG_SWIOTLB_DYNAMIC
1681 
1682 /**
1683  * swiotlb_del_transient() - delete a transient memory pool
1684  * @dev:	Device which mapped the buffer.
1685  * @tlb_addr:	Physical address within a bounce buffer.
1686  * @pool:       Pointer to the transient memory pool to be checked and deleted.
1687  *
1688  * Check whether the address belongs to a transient SWIOTLB memory pool.
1689  * If yes, then delete the pool.
1690  *
1691  * Return: %true if @tlb_addr belonged to a transient pool that was released.
1692  */
1693 static bool swiotlb_del_transient(struct device *dev, phys_addr_t tlb_addr,
1694 		struct io_tlb_pool *pool)
1695 {
1696 	if (!pool->transient)
1697 		return false;
1698 
1699 	dec_used(dev->dma_io_tlb_mem, pool->nslabs);
1700 	swiotlb_del_pool(dev, pool);
1701 	dec_transient_used(dev->dma_io_tlb_mem, pool->nslabs);
1702 	return true;
1703 }
1704 
1705 #else  /* !CONFIG_SWIOTLB_DYNAMIC */
1706 
1707 static inline bool swiotlb_del_transient(struct device *dev,
1708 		phys_addr_t tlb_addr, struct io_tlb_pool *pool)
1709 {
1710 	return false;
1711 }
1712 
1713 #endif	/* CONFIG_SWIOTLB_DYNAMIC */
1714 
1715 /*
1716  * tlb_addr is the physical address of the bounce buffer to unmap.
1717  */
1718 void __swiotlb_tbl_unmap_single(struct device *dev, phys_addr_t tlb_addr,
1719 		size_t mapping_size, enum dma_data_direction dir,
1720 		unsigned long attrs, struct io_tlb_pool *pool)
1721 {
1722 	/*
1723 	 * First, sync the memory before unmapping the entry
1724 	 */
1725 	if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
1726 	    (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL))
1727 		swiotlb_bounce(dev, tlb_addr, mapping_size,
1728 						DMA_FROM_DEVICE, pool);
1729 
1730 	if (swiotlb_del_transient(dev, tlb_addr, pool))
1731 		return;
1732 	swiotlb_release_slots(dev, tlb_addr, pool);
1733 }
1734 
1735 void __swiotlb_sync_single_for_device(struct device *dev, phys_addr_t tlb_addr,
1736 		size_t size, enum dma_data_direction dir,
1737 		struct io_tlb_pool *pool)
1738 {
1739 	if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL)
1740 		swiotlb_bounce(dev, tlb_addr, size, DMA_TO_DEVICE, pool);
1741 	else
1742 		BUG_ON(dir != DMA_FROM_DEVICE);
1743 }
1744 
1745 void __swiotlb_sync_single_for_cpu(struct device *dev, phys_addr_t tlb_addr,
1746 		size_t size, enum dma_data_direction dir,
1747 		struct io_tlb_pool *pool)
1748 {
1749 	if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
1750 		swiotlb_bounce(dev, tlb_addr, size, DMA_FROM_DEVICE, pool);
1751 	else
1752 		BUG_ON(dir != DMA_TO_DEVICE);
1753 }
1754 
1755 /*
1756  * Create a swiotlb mapping for the buffer at @paddr, and in case of DMAing
1757  * to the device copy the data into it as well.
1758  */
1759 dma_addr_t swiotlb_map(struct device *dev, phys_addr_t paddr, size_t size,
1760 		enum dma_data_direction dir, unsigned long attrs)
1761 {
1762 	phys_addr_t swiotlb_addr;
1763 	dma_addr_t dma_addr;
1764 
1765 	trace_swiotlb_bounced(dev, phys_to_dma(dev, paddr), size);
1766 
1767 	swiotlb_addr = swiotlb_tbl_map_single(dev, paddr, size, 0, dir, &attrs);
1768 	if (swiotlb_addr == (phys_addr_t)DMA_MAPPING_ERROR)
1769 		return DMA_MAPPING_ERROR;
1770 
1771 	if (attrs & DMA_ATTR_CC_SHARED)
1772 		dma_addr = phys_to_dma_unencrypted(dev, swiotlb_addr);
1773 	else
1774 		dma_addr = phys_to_dma_encrypted(dev, swiotlb_addr);
1775 
1776 	if (unlikely(!dma_capable(dev, dma_addr, size, true, attrs))) {
1777 		__swiotlb_tbl_unmap_single(dev, swiotlb_addr, size, dir,
1778 			attrs | DMA_ATTR_SKIP_CPU_SYNC,
1779 			swiotlb_find_pool(dev, swiotlb_addr));
1780 		dev_WARN_ONCE(dev, 1,
1781 			"swiotlb addr %pad+%zu overflow (mask %llx, bus limit %llx).\n",
1782 			&dma_addr, size, *dev->dma_mask, dev->bus_dma_limit);
1783 		return DMA_MAPPING_ERROR;
1784 	}
1785 
1786 	if (!dev_is_dma_coherent(dev) && !(attrs & DMA_ATTR_SKIP_CPU_SYNC)) {
1787 		arch_sync_dma_for_device(swiotlb_addr, size, dir);
1788 		arch_sync_dma_flush();
1789 	}
1790 	return dma_addr;
1791 }
1792 
1793 size_t swiotlb_max_mapping_size(struct device *dev)
1794 {
1795 	int min_align_mask = dma_get_min_align_mask(dev);
1796 	int min_align = 0;
1797 
1798 	/*
1799 	 * swiotlb_find_slots() skips slots according to
1800 	 * min align mask. This affects max mapping size.
1801 	 * Take it into acount here.
1802 	 */
1803 	if (min_align_mask)
1804 		min_align = roundup(min_align_mask, IO_TLB_SIZE);
1805 
1806 	return ((size_t)IO_TLB_SIZE) * IO_TLB_SEGSIZE - min_align;
1807 }
1808 
1809 /**
1810  * is_swiotlb_allocated() - check if the default software IO TLB is initialized
1811  */
1812 bool is_swiotlb_allocated(void)
1813 {
1814 	return io_tlb_default_mem.nslabs;
1815 }
1816 
1817 bool is_swiotlb_active(struct device *dev)
1818 {
1819 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
1820 
1821 	return mem && mem->nslabs;
1822 }
1823 
1824 /**
1825  * default_swiotlb_base() - get the base address of the default SWIOTLB
1826  *
1827  * Get the lowest physical address used by the default software IO TLB pool.
1828  */
1829 phys_addr_t default_swiotlb_base(void)
1830 {
1831 #ifdef CONFIG_SWIOTLB_DYNAMIC
1832 	io_tlb_default_mem.can_grow = false;
1833 #endif
1834 	return io_tlb_default_mem.defpool.start;
1835 }
1836 
1837 /**
1838  * default_swiotlb_limit() - get the address limit of the default SWIOTLB
1839  *
1840  * Get the highest physical address used by the default software IO TLB pool.
1841  */
1842 phys_addr_t default_swiotlb_limit(void)
1843 {
1844 #ifdef CONFIG_SWIOTLB_DYNAMIC
1845 	if (io_tlb_default_mem.can_grow)
1846 		return io_tlb_default_mem.phys_limit;
1847 #endif
1848 	return io_tlb_default_mem.defpool.end - 1;
1849 }
1850 
1851 #ifdef CONFIG_DEBUG_FS
1852 #ifdef CONFIG_SWIOTLB_DYNAMIC
1853 static unsigned long mem_transient_used(struct io_tlb_mem *mem)
1854 {
1855 	return atomic_long_read(&mem->transient_nslabs);
1856 }
1857 
1858 static int io_tlb_transient_used_get(void *data, u64 *val)
1859 {
1860 	struct io_tlb_mem *mem = data;
1861 
1862 	*val = mem_transient_used(mem);
1863 	return 0;
1864 }
1865 
1866 DEFINE_DEBUGFS_ATTRIBUTE(fops_io_tlb_transient_used, io_tlb_transient_used_get,
1867 			 NULL, "%llu\n");
1868 #endif /* CONFIG_SWIOTLB_DYNAMIC */
1869 
1870 static int io_tlb_used_get(void *data, u64 *val)
1871 {
1872 	struct io_tlb_mem *mem = data;
1873 
1874 	*val = mem_used(mem);
1875 	return 0;
1876 }
1877 
1878 static int io_tlb_hiwater_get(void *data, u64 *val)
1879 {
1880 	struct io_tlb_mem *mem = data;
1881 
1882 	*val = atomic_long_read(&mem->used_hiwater);
1883 	return 0;
1884 }
1885 
1886 static int io_tlb_hiwater_set(void *data, u64 val)
1887 {
1888 	struct io_tlb_mem *mem = data;
1889 
1890 	/* Only allow setting to zero */
1891 	if (val != 0)
1892 		return -EINVAL;
1893 
1894 	atomic_long_set(&mem->used_hiwater, val);
1895 	return 0;
1896 }
1897 
1898 DEFINE_DEBUGFS_ATTRIBUTE(fops_io_tlb_used, io_tlb_used_get, NULL, "%llu\n");
1899 DEFINE_DEBUGFS_ATTRIBUTE(fops_io_tlb_hiwater, io_tlb_hiwater_get,
1900 				io_tlb_hiwater_set, "%llu\n");
1901 
1902 static void swiotlb_create_debugfs_files(struct io_tlb_mem *mem,
1903 					 const char *dirname)
1904 {
1905 	mem->debugfs = debugfs_create_dir(dirname, io_tlb_default_mem.debugfs);
1906 	if (!mem->nslabs)
1907 		return;
1908 
1909 	debugfs_create_ulong("io_tlb_nslabs", 0400, mem->debugfs, &mem->nslabs);
1910 	debugfs_create_file("io_tlb_used", 0400, mem->debugfs, mem,
1911 			&fops_io_tlb_used);
1912 	debugfs_create_file("io_tlb_used_hiwater", 0600, mem->debugfs, mem,
1913 			&fops_io_tlb_hiwater);
1914 #ifdef CONFIG_SWIOTLB_DYNAMIC
1915 	debugfs_create_file("io_tlb_transient_nslabs", 0400, mem->debugfs,
1916 			    mem, &fops_io_tlb_transient_used);
1917 #endif
1918 }
1919 
1920 static int __init swiotlb_create_default_debugfs(void)
1921 {
1922 	swiotlb_create_debugfs_files(&io_tlb_default_mem, "swiotlb");
1923 	return 0;
1924 }
1925 
1926 late_initcall(swiotlb_create_default_debugfs);
1927 
1928 #else  /* !CONFIG_DEBUG_FS */
1929 
1930 static inline void swiotlb_create_debugfs_files(struct io_tlb_mem *mem,
1931 						const char *dirname)
1932 {
1933 }
1934 
1935 #endif	/* CONFIG_DEBUG_FS */
1936 
1937 #ifdef CONFIG_DMA_RESTRICTED_POOL
1938 
1939 struct page *swiotlb_alloc(struct device *dev, size_t size, unsigned long attrs)
1940 {
1941 	struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
1942 	struct io_tlb_pool *pool;
1943 	phys_addr_t tlb_addr;
1944 	unsigned int align;
1945 	int index;
1946 
1947 	if (!mem)
1948 		return NULL;
1949 
1950 	if (mem->cc_shared != !!(attrs & __DMA_ATTR_ALLOC_CC_SHARED))
1951 		return NULL;
1952 
1953 	align = (1 << (get_order(size) + PAGE_SHIFT)) - 1;
1954 	index = swiotlb_find_slots(dev, 0, size, align, &pool);
1955 	if (index == -1)
1956 		return NULL;
1957 
1958 	tlb_addr = slot_addr(pool->start, index);
1959 	if (unlikely(!PAGE_ALIGNED(tlb_addr))) {
1960 		dev_WARN_ONCE(dev, 1, "Cannot allocate pages from non page-aligned swiotlb addr 0x%pa.\n",
1961 			      &tlb_addr);
1962 		swiotlb_release_slots(dev, tlb_addr, pool);
1963 		return NULL;
1964 	}
1965 
1966 	return pfn_to_page(PFN_DOWN(tlb_addr));
1967 }
1968 
1969 bool swiotlb_free(struct device *dev, struct page *page, size_t size)
1970 {
1971 	phys_addr_t tlb_addr = page_to_phys(page);
1972 	struct io_tlb_pool *pool;
1973 
1974 	pool = swiotlb_find_pool(dev, tlb_addr);
1975 	if (!pool)
1976 		return false;
1977 
1978 	swiotlb_release_slots(dev, tlb_addr, pool);
1979 
1980 	return true;
1981 }
1982 
1983 void swiotlb_free_from_pool(struct device *dev,
1984 		phys_addr_t tlb_addr, struct io_tlb_pool *pool)
1985 {
1986 	swiotlb_release_slots(dev, tlb_addr, pool);
1987 }
1988 
1989 static int rmem_swiotlb_device_init(struct reserved_mem *rmem,
1990 				    struct device *dev)
1991 {
1992 	struct io_tlb_mem *mem = rmem->priv;
1993 	unsigned long nslabs = rmem->size >> IO_TLB_SHIFT;
1994 
1995 	/* Set Per-device io tlb area to one */
1996 	unsigned int nareas = 1;
1997 
1998 	if (PageHighMem(pfn_to_page(PHYS_PFN(rmem->base)))) {
1999 		dev_err(dev, "Restricted DMA pool must be accessible within the linear mapping.");
2000 		return -EINVAL;
2001 	}
2002 
2003 	/*
2004 	 * Since multiple devices can share the same pool, the private data,
2005 	 * io_tlb_mem struct, will be initialized by the first device attached
2006 	 * to it.
2007 	 */
2008 	if (!mem) {
2009 		struct io_tlb_pool *pool;
2010 
2011 		mem = kzalloc_obj(*mem);
2012 		if (!mem)
2013 			return -ENOMEM;
2014 		pool = &mem->defpool;
2015 
2016 		pool->slots = kzalloc_objs(*pool->slots, nslabs);
2017 		if (!pool->slots) {
2018 			kfree(mem);
2019 			return -ENOMEM;
2020 		}
2021 
2022 		pool->areas = kzalloc_objs(*pool->areas, nareas);
2023 		if (!pool->areas) {
2024 			kfree(pool->slots);
2025 			kfree(mem);
2026 			return -ENOMEM;
2027 		}
2028 		/*
2029 		 * if platform supports memory encryption,
2030 		 * restricted mem pool is shared by default
2031 		 */
2032 		if (cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
2033 			int ret;
2034 
2035 			mem->cc_shared = true;
2036 			ret = set_memory_decrypted((unsigned long)phys_to_virt(rmem->base),
2037 						   rmem->size >> PAGE_SHIFT);
2038 			if (ret) {
2039 				dev_err(dev, "Failed to decrypt restricted DMA pool\n");
2040 				kfree(pool->areas);
2041 				kfree(pool->slots);
2042 				kfree(mem);
2043 				return ret;
2044 			}
2045 		} else {
2046 			mem->cc_shared = false;
2047 		}
2048 
2049 		swiotlb_init_io_tlb_pool(pool, rmem->base, phys_to_virt(rmem->base),
2050 					 nslabs, false, nareas);
2051 		mem->force_bounce = true;
2052 		mem->for_alloc = true;
2053 #ifdef CONFIG_SWIOTLB_DYNAMIC
2054 		spin_lock_init(&mem->lock);
2055 		INIT_LIST_HEAD_RCU(&mem->pools);
2056 #endif
2057 		add_mem_pool(mem, pool);
2058 
2059 		rmem->priv = mem;
2060 
2061 		swiotlb_create_debugfs_files(mem, rmem->name);
2062 	}
2063 
2064 	dev->dma_io_tlb_mem = mem;
2065 
2066 	return 0;
2067 }
2068 
2069 static void rmem_swiotlb_device_release(struct reserved_mem *rmem,
2070 					struct device *dev)
2071 {
2072 	dev->dma_io_tlb_mem = &io_tlb_default_mem;
2073 }
2074 
2075 static int __init rmem_swiotlb_setup(unsigned long node,
2076 				     struct reserved_mem *rmem)
2077 {
2078 	if (of_get_flat_dt_prop(node, "reusable", NULL) ||
2079 	    of_get_flat_dt_prop(node, "linux,cma-default", NULL) ||
2080 	    of_get_flat_dt_prop(node, "linux,dma-default", NULL) ||
2081 	    of_get_flat_dt_prop(node, "no-map", NULL))
2082 		return -EINVAL;
2083 
2084 	pr_info("Reserved memory: created restricted DMA pool at %pa, size %llu KiB\n",
2085 		&rmem->base, (unsigned long long)(rmem->size / SZ_1K));
2086 	return 0;
2087 }
2088 
2089 static const struct reserved_mem_ops rmem_swiotlb_ops = {
2090 	.node_init = rmem_swiotlb_setup,
2091 	.device_init = rmem_swiotlb_device_init,
2092 	.device_release = rmem_swiotlb_device_release,
2093 };
2094 
2095 RESERVEDMEM_OF_DECLARE(dma, "restricted-dma-pool", &rmem_swiotlb_ops);
2096 #endif /* CONFIG_DMA_RESTRICTED_POOL */
2097