xref: /openbmc/linux/kernel/dma/swiotlb.c (revision 92614ad5)
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/dma-direct.h>
25 #include <linux/dma-map-ops.h>
26 #include <linux/mm.h>
27 #include <linux/export.h>
28 #include <linux/spinlock.h>
29 #include <linux/string.h>
30 #include <linux/swiotlb.h>
31 #include <linux/pfn.h>
32 #include <linux/types.h>
33 #include <linux/ctype.h>
34 #include <linux/highmem.h>
35 #include <linux/gfp.h>
36 #include <linux/scatterlist.h>
37 #include <linux/mem_encrypt.h>
38 #include <linux/set_memory.h>
39 #ifdef CONFIG_DEBUG_FS
40 #include <linux/debugfs.h>
41 #endif
42 
43 #include <asm/io.h>
44 #include <asm/dma.h>
45 
46 #include <linux/init.h>
47 #include <linux/memblock.h>
48 #include <linux/iommu-helper.h>
49 
50 #define CREATE_TRACE_POINTS
51 #include <trace/events/swiotlb.h>
52 
53 #define OFFSET(val,align) ((unsigned long)	\
54 	                   ( (val) & ( (align) - 1)))
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 enum swiotlb_force swiotlb_force;
66 
67 /*
68  * Used to do a quick range check in swiotlb_tbl_unmap_single and
69  * swiotlb_tbl_sync_single_*, to see if the memory was in fact allocated by this
70  * API.
71  */
72 phys_addr_t io_tlb_start, io_tlb_end;
73 
74 /*
75  * The number of IO TLB blocks (in groups of 64) between io_tlb_start and
76  * io_tlb_end.  This is command line adjustable via setup_io_tlb_npages.
77  */
78 static unsigned long io_tlb_nslabs;
79 
80 /*
81  * The number of used IO TLB block
82  */
83 static unsigned long io_tlb_used;
84 
85 /*
86  * This is a free list describing the number of free entries available from
87  * each index
88  */
89 static unsigned int *io_tlb_list;
90 static unsigned int io_tlb_index;
91 
92 /*
93  * Max segment that we can provide which (if pages are contingous) will
94  * not be bounced (unless SWIOTLB_FORCE is set).
95  */
96 static unsigned int max_segment;
97 
98 /*
99  * We need to save away the original address corresponding to a mapped entry
100  * for the sync operations.
101  */
102 #define INVALID_PHYS_ADDR (~(phys_addr_t)0)
103 static phys_addr_t *io_tlb_orig_addr;
104 
105 /*
106  * Protect the above data structures in the map and unmap calls
107  */
108 static DEFINE_SPINLOCK(io_tlb_lock);
109 
110 static int late_alloc;
111 
112 static int __init
113 setup_io_tlb_npages(char *str)
114 {
115 	if (isdigit(*str)) {
116 		io_tlb_nslabs = simple_strtoul(str, &str, 0);
117 		/* avoid tail segment of size < IO_TLB_SEGSIZE */
118 		io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
119 	}
120 	if (*str == ',')
121 		++str;
122 	if (!strcmp(str, "force")) {
123 		swiotlb_force = SWIOTLB_FORCE;
124 	} else if (!strcmp(str, "noforce")) {
125 		swiotlb_force = SWIOTLB_NO_FORCE;
126 		io_tlb_nslabs = 1;
127 	}
128 
129 	return 0;
130 }
131 early_param("swiotlb", setup_io_tlb_npages);
132 
133 static bool no_iotlb_memory;
134 
135 unsigned long swiotlb_nr_tbl(void)
136 {
137 	return unlikely(no_iotlb_memory) ? 0 : io_tlb_nslabs;
138 }
139 EXPORT_SYMBOL_GPL(swiotlb_nr_tbl);
140 
141 unsigned int swiotlb_max_segment(void)
142 {
143 	return unlikely(no_iotlb_memory) ? 0 : max_segment;
144 }
145 EXPORT_SYMBOL_GPL(swiotlb_max_segment);
146 
147 void swiotlb_set_max_segment(unsigned int val)
148 {
149 	if (swiotlb_force == SWIOTLB_FORCE)
150 		max_segment = 1;
151 	else
152 		max_segment = rounddown(val, PAGE_SIZE);
153 }
154 
155 unsigned long swiotlb_size_or_default(void)
156 {
157 	unsigned long size;
158 
159 	size = io_tlb_nslabs << IO_TLB_SHIFT;
160 
161 	return size ? size : (IO_TLB_DEFAULT_SIZE);
162 }
163 
164 void __init swiotlb_adjust_size(unsigned long new_size)
165 {
166 	unsigned long size;
167 
168 	/*
169 	 * If swiotlb parameter has not been specified, give a chance to
170 	 * architectures such as those supporting memory encryption to
171 	 * adjust/expand SWIOTLB size for their use.
172 	 */
173 	if (!io_tlb_nslabs) {
174 		size = ALIGN(new_size, 1 << IO_TLB_SHIFT);
175 		io_tlb_nslabs = size >> IO_TLB_SHIFT;
176 		io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
177 
178 		pr_info("SWIOTLB bounce buffer size adjusted to %luMB", size >> 20);
179 	}
180 }
181 
182 void swiotlb_print_info(void)
183 {
184 	unsigned long bytes = io_tlb_nslabs << IO_TLB_SHIFT;
185 
186 	if (no_iotlb_memory) {
187 		pr_warn("No low mem\n");
188 		return;
189 	}
190 
191 	pr_info("mapped [mem %pa-%pa] (%luMB)\n", &io_tlb_start, &io_tlb_end,
192 	       bytes >> 20);
193 }
194 
195 /*
196  * Early SWIOTLB allocation may be too early to allow an architecture to
197  * perform the desired operations.  This function allows the architecture to
198  * call SWIOTLB when the operations are possible.  It needs to be called
199  * before the SWIOTLB memory is used.
200  */
201 void __init swiotlb_update_mem_attributes(void)
202 {
203 	void *vaddr;
204 	unsigned long bytes;
205 
206 	if (no_iotlb_memory || late_alloc)
207 		return;
208 
209 	vaddr = phys_to_virt(io_tlb_start);
210 	bytes = PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT);
211 	set_memory_decrypted((unsigned long)vaddr, bytes >> PAGE_SHIFT);
212 	memset(vaddr, 0, bytes);
213 }
214 
215 int __init swiotlb_init_with_tbl(char *tlb, unsigned long nslabs, int verbose)
216 {
217 	unsigned long i, bytes;
218 	size_t alloc_size;
219 
220 	bytes = nslabs << IO_TLB_SHIFT;
221 
222 	io_tlb_nslabs = nslabs;
223 	io_tlb_start = __pa(tlb);
224 	io_tlb_end = io_tlb_start + bytes;
225 
226 	/*
227 	 * Allocate and initialize the free list array.  This array is used
228 	 * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
229 	 * between io_tlb_start and io_tlb_end.
230 	 */
231 	alloc_size = PAGE_ALIGN(io_tlb_nslabs * sizeof(int));
232 	io_tlb_list = memblock_alloc(alloc_size, PAGE_SIZE);
233 	if (!io_tlb_list)
234 		panic("%s: Failed to allocate %zu bytes align=0x%lx\n",
235 		      __func__, alloc_size, PAGE_SIZE);
236 
237 	alloc_size = PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t));
238 	io_tlb_orig_addr = memblock_alloc(alloc_size, PAGE_SIZE);
239 	if (!io_tlb_orig_addr)
240 		panic("%s: Failed to allocate %zu bytes align=0x%lx\n",
241 		      __func__, alloc_size, PAGE_SIZE);
242 
243 	for (i = 0; i < io_tlb_nslabs; i++) {
244 		io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE);
245 		io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
246 	}
247 	io_tlb_index = 0;
248 	no_iotlb_memory = false;
249 
250 	if (verbose)
251 		swiotlb_print_info();
252 
253 	swiotlb_set_max_segment(io_tlb_nslabs << IO_TLB_SHIFT);
254 	return 0;
255 }
256 
257 /*
258  * Statically reserve bounce buffer space and initialize bounce buffer data
259  * structures for the software IO TLB used to implement the DMA API.
260  */
261 void  __init
262 swiotlb_init(int verbose)
263 {
264 	size_t default_size = IO_TLB_DEFAULT_SIZE;
265 	unsigned char *vstart;
266 	unsigned long bytes;
267 
268 	if (!io_tlb_nslabs) {
269 		io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
270 		io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
271 	}
272 
273 	bytes = io_tlb_nslabs << IO_TLB_SHIFT;
274 
275 	/* Get IO TLB memory from the low pages */
276 	vstart = memblock_alloc_low(PAGE_ALIGN(bytes), PAGE_SIZE);
277 	if (vstart && !swiotlb_init_with_tbl(vstart, io_tlb_nslabs, verbose))
278 		return;
279 
280 	if (io_tlb_start) {
281 		memblock_free_early(io_tlb_start,
282 				    PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
283 		io_tlb_start = 0;
284 	}
285 	pr_warn("Cannot allocate buffer");
286 	no_iotlb_memory = true;
287 }
288 
289 /*
290  * Systems with larger DMA zones (those that don't support ISA) can
291  * initialize the swiotlb later using the slab allocator if needed.
292  * This should be just like above, but with some error catching.
293  */
294 int
295 swiotlb_late_init_with_default_size(size_t default_size)
296 {
297 	unsigned long bytes, req_nslabs = io_tlb_nslabs;
298 	unsigned char *vstart = NULL;
299 	unsigned int order;
300 	int rc = 0;
301 
302 	if (!io_tlb_nslabs) {
303 		io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
304 		io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
305 	}
306 
307 	/*
308 	 * Get IO TLB memory from the low pages
309 	 */
310 	order = get_order(io_tlb_nslabs << IO_TLB_SHIFT);
311 	io_tlb_nslabs = SLABS_PER_PAGE << order;
312 	bytes = io_tlb_nslabs << IO_TLB_SHIFT;
313 
314 	while ((SLABS_PER_PAGE << order) > IO_TLB_MIN_SLABS) {
315 		vstart = (void *)__get_free_pages(GFP_DMA | __GFP_NOWARN,
316 						  order);
317 		if (vstart)
318 			break;
319 		order--;
320 	}
321 
322 	if (!vstart) {
323 		io_tlb_nslabs = req_nslabs;
324 		return -ENOMEM;
325 	}
326 	if (order != get_order(bytes)) {
327 		pr_warn("only able to allocate %ld MB\n",
328 			(PAGE_SIZE << order) >> 20);
329 		io_tlb_nslabs = SLABS_PER_PAGE << order;
330 	}
331 	rc = swiotlb_late_init_with_tbl(vstart, io_tlb_nslabs);
332 	if (rc)
333 		free_pages((unsigned long)vstart, order);
334 
335 	return rc;
336 }
337 
338 static void swiotlb_cleanup(void)
339 {
340 	io_tlb_end = 0;
341 	io_tlb_start = 0;
342 	io_tlb_nslabs = 0;
343 	max_segment = 0;
344 }
345 
346 int
347 swiotlb_late_init_with_tbl(char *tlb, unsigned long nslabs)
348 {
349 	unsigned long i, bytes;
350 
351 	bytes = nslabs << IO_TLB_SHIFT;
352 
353 	io_tlb_nslabs = nslabs;
354 	io_tlb_start = virt_to_phys(tlb);
355 	io_tlb_end = io_tlb_start + bytes;
356 
357 	set_memory_decrypted((unsigned long)tlb, bytes >> PAGE_SHIFT);
358 	memset(tlb, 0, bytes);
359 
360 	/*
361 	 * Allocate and initialize the free list array.  This array is used
362 	 * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
363 	 * between io_tlb_start and io_tlb_end.
364 	 */
365 	io_tlb_list = (unsigned int *)__get_free_pages(GFP_KERNEL,
366 	                              get_order(io_tlb_nslabs * sizeof(int)));
367 	if (!io_tlb_list)
368 		goto cleanup3;
369 
370 	io_tlb_orig_addr = (phys_addr_t *)
371 		__get_free_pages(GFP_KERNEL,
372 				 get_order(io_tlb_nslabs *
373 					   sizeof(phys_addr_t)));
374 	if (!io_tlb_orig_addr)
375 		goto cleanup4;
376 
377 	for (i = 0; i < io_tlb_nslabs; i++) {
378 		io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE);
379 		io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
380 	}
381 	io_tlb_index = 0;
382 	no_iotlb_memory = false;
383 
384 	swiotlb_print_info();
385 
386 	late_alloc = 1;
387 
388 	swiotlb_set_max_segment(io_tlb_nslabs << IO_TLB_SHIFT);
389 
390 	return 0;
391 
392 cleanup4:
393 	free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
394 	                                                 sizeof(int)));
395 	io_tlb_list = NULL;
396 cleanup3:
397 	swiotlb_cleanup();
398 	return -ENOMEM;
399 }
400 
401 void __init swiotlb_exit(void)
402 {
403 	if (!io_tlb_orig_addr)
404 		return;
405 
406 	if (late_alloc) {
407 		free_pages((unsigned long)io_tlb_orig_addr,
408 			   get_order(io_tlb_nslabs * sizeof(phys_addr_t)));
409 		free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
410 								 sizeof(int)));
411 		free_pages((unsigned long)phys_to_virt(io_tlb_start),
412 			   get_order(io_tlb_nslabs << IO_TLB_SHIFT));
413 	} else {
414 		memblock_free_late(__pa(io_tlb_orig_addr),
415 				   PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)));
416 		memblock_free_late(__pa(io_tlb_list),
417 				   PAGE_ALIGN(io_tlb_nslabs * sizeof(int)));
418 		memblock_free_late(io_tlb_start,
419 				   PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
420 	}
421 	swiotlb_cleanup();
422 }
423 
424 /*
425  * Bounce: copy the swiotlb buffer from or back to the original dma location
426  */
427 static void swiotlb_bounce(phys_addr_t orig_addr, phys_addr_t tlb_addr,
428 			   size_t size, enum dma_data_direction dir)
429 {
430 	unsigned long pfn = PFN_DOWN(orig_addr);
431 	unsigned char *vaddr = phys_to_virt(tlb_addr);
432 
433 	if (PageHighMem(pfn_to_page(pfn))) {
434 		/* The buffer does not have a mapping.  Map it in and copy */
435 		unsigned int offset = orig_addr & ~PAGE_MASK;
436 		char *buffer;
437 		unsigned int sz = 0;
438 		unsigned long flags;
439 
440 		while (size) {
441 			sz = min_t(size_t, PAGE_SIZE - offset, size);
442 
443 			local_irq_save(flags);
444 			buffer = kmap_atomic(pfn_to_page(pfn));
445 			if (dir == DMA_TO_DEVICE)
446 				memcpy(vaddr, buffer + offset, sz);
447 			else
448 				memcpy(buffer + offset, vaddr, sz);
449 			kunmap_atomic(buffer);
450 			local_irq_restore(flags);
451 
452 			size -= sz;
453 			pfn++;
454 			vaddr += sz;
455 			offset = 0;
456 		}
457 	} else if (dir == DMA_TO_DEVICE) {
458 		memcpy(vaddr, phys_to_virt(orig_addr), size);
459 	} else {
460 		memcpy(phys_to_virt(orig_addr), vaddr, size);
461 	}
462 }
463 
464 phys_addr_t swiotlb_tbl_map_single(struct device *hwdev, phys_addr_t orig_addr,
465 		size_t mapping_size, size_t alloc_size,
466 		enum dma_data_direction dir, unsigned long attrs)
467 {
468 	dma_addr_t tbl_dma_addr = phys_to_dma_unencrypted(hwdev, io_tlb_start);
469 	unsigned long flags;
470 	phys_addr_t tlb_addr;
471 	unsigned int nslots, stride, index, wrap;
472 	int i;
473 	unsigned long mask;
474 	unsigned long offset_slots;
475 	unsigned long max_slots;
476 	unsigned long tmp_io_tlb_used;
477 
478 	if (no_iotlb_memory)
479 		panic("Can not allocate SWIOTLB buffer earlier and can't now provide you with the DMA bounce buffer");
480 
481 	if (mem_encrypt_active())
482 		pr_warn_once("Memory encryption is active and system is using DMA bounce buffers\n");
483 
484 	if (mapping_size > alloc_size) {
485 		dev_warn_once(hwdev, "Invalid sizes (mapping: %zd bytes, alloc: %zd bytes)",
486 			      mapping_size, alloc_size);
487 		return (phys_addr_t)DMA_MAPPING_ERROR;
488 	}
489 
490 	mask = dma_get_seg_boundary(hwdev);
491 
492 	tbl_dma_addr &= mask;
493 
494 	offset_slots = ALIGN(tbl_dma_addr, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
495 
496 	/*
497 	 * Carefully handle integer overflow which can occur when mask == ~0UL.
498 	 */
499 	max_slots = mask + 1
500 		    ? ALIGN(mask + 1, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT
501 		    : 1UL << (BITS_PER_LONG - IO_TLB_SHIFT);
502 
503 	/*
504 	 * For mappings greater than or equal to a page, we limit the stride
505 	 * (and hence alignment) to a page size.
506 	 */
507 	nslots = ALIGN(alloc_size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
508 	if (alloc_size >= PAGE_SIZE)
509 		stride = (1 << (PAGE_SHIFT - IO_TLB_SHIFT));
510 	else
511 		stride = 1;
512 
513 	BUG_ON(!nslots);
514 
515 	/*
516 	 * Find suitable number of IO TLB entries size that will fit this
517 	 * request and allocate a buffer from that IO TLB pool.
518 	 */
519 	spin_lock_irqsave(&io_tlb_lock, flags);
520 
521 	if (unlikely(nslots > io_tlb_nslabs - io_tlb_used))
522 		goto not_found;
523 
524 	index = ALIGN(io_tlb_index, stride);
525 	if (index >= io_tlb_nslabs)
526 		index = 0;
527 	wrap = index;
528 
529 	do {
530 		while (iommu_is_span_boundary(index, nslots, offset_slots,
531 					      max_slots)) {
532 			index += stride;
533 			if (index >= io_tlb_nslabs)
534 				index = 0;
535 			if (index == wrap)
536 				goto not_found;
537 		}
538 
539 		/*
540 		 * If we find a slot that indicates we have 'nslots' number of
541 		 * contiguous buffers, we allocate the buffers from that slot
542 		 * and mark the entries as '0' indicating unavailable.
543 		 */
544 		if (io_tlb_list[index] >= nslots) {
545 			int count = 0;
546 
547 			for (i = index; i < (int) (index + nslots); i++)
548 				io_tlb_list[i] = 0;
549 			for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE - 1) && io_tlb_list[i]; i--)
550 				io_tlb_list[i] = ++count;
551 			tlb_addr = io_tlb_start + (index << IO_TLB_SHIFT);
552 
553 			/*
554 			 * Update the indices to avoid searching in the next
555 			 * round.
556 			 */
557 			io_tlb_index = ((index + nslots) < io_tlb_nslabs
558 					? (index + nslots) : 0);
559 
560 			goto found;
561 		}
562 		index += stride;
563 		if (index >= io_tlb_nslabs)
564 			index = 0;
565 	} while (index != wrap);
566 
567 not_found:
568 	tmp_io_tlb_used = io_tlb_used;
569 
570 	spin_unlock_irqrestore(&io_tlb_lock, flags);
571 	if (!(attrs & DMA_ATTR_NO_WARN) && printk_ratelimit())
572 		dev_warn(hwdev, "swiotlb buffer is full (sz: %zd bytes), total %lu (slots), used %lu (slots)\n",
573 			 alloc_size, io_tlb_nslabs, tmp_io_tlb_used);
574 	return (phys_addr_t)DMA_MAPPING_ERROR;
575 found:
576 	io_tlb_used += nslots;
577 	spin_unlock_irqrestore(&io_tlb_lock, flags);
578 
579 	/*
580 	 * Save away the mapping from the original address to the DMA address.
581 	 * This is needed when we sync the memory.  Then we sync the buffer if
582 	 * needed.
583 	 */
584 	for (i = 0; i < nslots; i++)
585 		io_tlb_orig_addr[index+i] = orig_addr + (i << IO_TLB_SHIFT);
586 	if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
587 	    (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL))
588 		swiotlb_bounce(orig_addr, tlb_addr, mapping_size, DMA_TO_DEVICE);
589 
590 	return tlb_addr;
591 }
592 
593 /*
594  * tlb_addr is the physical address of the bounce buffer to unmap.
595  */
596 void swiotlb_tbl_unmap_single(struct device *hwdev, phys_addr_t tlb_addr,
597 			      size_t mapping_size, size_t alloc_size,
598 			      enum dma_data_direction dir, unsigned long attrs)
599 {
600 	unsigned long flags;
601 	int i, count, nslots = ALIGN(alloc_size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
602 	int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT;
603 	phys_addr_t orig_addr = io_tlb_orig_addr[index];
604 
605 	/*
606 	 * First, sync the memory before unmapping the entry
607 	 */
608 	if (orig_addr != INVALID_PHYS_ADDR &&
609 	    !(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
610 	    ((dir == DMA_FROM_DEVICE) || (dir == DMA_BIDIRECTIONAL)))
611 		swiotlb_bounce(orig_addr, tlb_addr, mapping_size, DMA_FROM_DEVICE);
612 
613 	/*
614 	 * Return the buffer to the free list by setting the corresponding
615 	 * entries to indicate the number of contiguous entries available.
616 	 * While returning the entries to the free list, we merge the entries
617 	 * with slots below and above the pool being returned.
618 	 */
619 	spin_lock_irqsave(&io_tlb_lock, flags);
620 	{
621 		count = ((index + nslots) < ALIGN(index + 1, IO_TLB_SEGSIZE) ?
622 			 io_tlb_list[index + nslots] : 0);
623 		/*
624 		 * Step 1: return the slots to the free list, merging the
625 		 * slots with superceeding slots
626 		 */
627 		for (i = index + nslots - 1; i >= index; i--) {
628 			io_tlb_list[i] = ++count;
629 			io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
630 		}
631 		/*
632 		 * Step 2: merge the returned slots with the preceding slots,
633 		 * if available (non zero)
634 		 */
635 		for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE -1) && io_tlb_list[i]; i--)
636 			io_tlb_list[i] = ++count;
637 
638 		io_tlb_used -= nslots;
639 	}
640 	spin_unlock_irqrestore(&io_tlb_lock, flags);
641 }
642 
643 void swiotlb_tbl_sync_single(struct device *hwdev, phys_addr_t tlb_addr,
644 			     size_t size, enum dma_data_direction dir,
645 			     enum dma_sync_target target)
646 {
647 	int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT;
648 	phys_addr_t orig_addr = io_tlb_orig_addr[index];
649 
650 	if (orig_addr == INVALID_PHYS_ADDR)
651 		return;
652 	orig_addr += (unsigned long)tlb_addr & ((1 << IO_TLB_SHIFT) - 1);
653 
654 	switch (target) {
655 	case SYNC_FOR_CPU:
656 		if (likely(dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL))
657 			swiotlb_bounce(orig_addr, tlb_addr,
658 				       size, DMA_FROM_DEVICE);
659 		else
660 			BUG_ON(dir != DMA_TO_DEVICE);
661 		break;
662 	case SYNC_FOR_DEVICE:
663 		if (likely(dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL))
664 			swiotlb_bounce(orig_addr, tlb_addr,
665 				       size, DMA_TO_DEVICE);
666 		else
667 			BUG_ON(dir != DMA_FROM_DEVICE);
668 		break;
669 	default:
670 		BUG();
671 	}
672 }
673 
674 /*
675  * Create a swiotlb mapping for the buffer at @paddr, and in case of DMAing
676  * to the device copy the data into it as well.
677  */
678 dma_addr_t swiotlb_map(struct device *dev, phys_addr_t paddr, size_t size,
679 		enum dma_data_direction dir, unsigned long attrs)
680 {
681 	phys_addr_t swiotlb_addr;
682 	dma_addr_t dma_addr;
683 
684 	trace_swiotlb_bounced(dev, phys_to_dma(dev, paddr), size,
685 			      swiotlb_force);
686 
687 	swiotlb_addr = swiotlb_tbl_map_single(dev, paddr, size, size, dir,
688 			attrs);
689 	if (swiotlb_addr == (phys_addr_t)DMA_MAPPING_ERROR)
690 		return DMA_MAPPING_ERROR;
691 
692 	/* Ensure that the address returned is DMA'ble */
693 	dma_addr = phys_to_dma_unencrypted(dev, swiotlb_addr);
694 	if (unlikely(!dma_capable(dev, dma_addr, size, true))) {
695 		swiotlb_tbl_unmap_single(dev, swiotlb_addr, size, size, dir,
696 			attrs | DMA_ATTR_SKIP_CPU_SYNC);
697 		dev_WARN_ONCE(dev, 1,
698 			"swiotlb addr %pad+%zu overflow (mask %llx, bus limit %llx).\n",
699 			&dma_addr, size, *dev->dma_mask, dev->bus_dma_limit);
700 		return DMA_MAPPING_ERROR;
701 	}
702 
703 	if (!dev_is_dma_coherent(dev) && !(attrs & DMA_ATTR_SKIP_CPU_SYNC))
704 		arch_sync_dma_for_device(swiotlb_addr, size, dir);
705 	return dma_addr;
706 }
707 
708 size_t swiotlb_max_mapping_size(struct device *dev)
709 {
710 	return ((size_t)1 << IO_TLB_SHIFT) * IO_TLB_SEGSIZE;
711 }
712 
713 bool is_swiotlb_active(void)
714 {
715 	/*
716 	 * When SWIOTLB is initialized, even if io_tlb_start points to physical
717 	 * address zero, io_tlb_end surely doesn't.
718 	 */
719 	return io_tlb_end != 0;
720 }
721 
722 #ifdef CONFIG_DEBUG_FS
723 
724 static int __init swiotlb_create_debugfs(void)
725 {
726 	struct dentry *root;
727 
728 	root = debugfs_create_dir("swiotlb", NULL);
729 	debugfs_create_ulong("io_tlb_nslabs", 0400, root, &io_tlb_nslabs);
730 	debugfs_create_ulong("io_tlb_used", 0400, root, &io_tlb_used);
731 	return 0;
732 }
733 
734 late_initcall(swiotlb_create_debugfs);
735 
736 #endif
737