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