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