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