xref: /openbmc/linux/kernel/dma/swiotlb.c (revision 5f30b2e8)
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 
38 #include <asm/io.h>
39 #include <asm/dma.h>
40 
41 #include <linux/init.h>
42 #include <linux/bootmem.h>
43 #include <linux/iommu-helper.h>
44 
45 #define CREATE_TRACE_POINTS
46 #include <trace/events/swiotlb.h>
47 
48 #define OFFSET(val,align) ((unsigned long)	\
49 	                   ( (val) & ( (align) - 1)))
50 
51 #define SLABS_PER_PAGE (1 << (PAGE_SHIFT - IO_TLB_SHIFT))
52 
53 /*
54  * Minimum IO TLB size to bother booting with.  Systems with mainly
55  * 64bit capable cards will only lightly use the swiotlb.  If we can't
56  * allocate a contiguous 1MB, we're probably in trouble anyway.
57  */
58 #define IO_TLB_MIN_SLABS ((1<<20) >> IO_TLB_SHIFT)
59 
60 enum swiotlb_force swiotlb_force;
61 
62 /*
63  * Used to do a quick range check in swiotlb_tbl_unmap_single and
64  * swiotlb_tbl_sync_single_*, to see if the memory was in fact allocated by this
65  * API.
66  */
67 static phys_addr_t io_tlb_start, io_tlb_end;
68 
69 /*
70  * The number of IO TLB blocks (in groups of 64) between io_tlb_start and
71  * io_tlb_end.  This is command line adjustable via setup_io_tlb_npages.
72  */
73 static unsigned long io_tlb_nslabs;
74 
75 /*
76  * When the IOMMU overflows we return a fallback buffer. This sets the size.
77  */
78 static unsigned long io_tlb_overflow = 32*1024;
79 
80 static phys_addr_t io_tlb_overflow_buffer;
81 
82 /*
83  * This is a free list describing the number of free entries available from
84  * each index
85  */
86 static unsigned int *io_tlb_list;
87 static unsigned int io_tlb_index;
88 
89 /*
90  * Max segment that we can provide which (if pages are contingous) will
91  * not be bounced (unless SWIOTLB_FORCE is set).
92  */
93 unsigned int max_segment;
94 
95 /*
96  * We need to save away the original address corresponding to a mapped entry
97  * for the sync operations.
98  */
99 #define INVALID_PHYS_ADDR (~(phys_addr_t)0)
100 static phys_addr_t *io_tlb_orig_addr;
101 
102 /*
103  * Protect the above data structures in the map and unmap calls
104  */
105 static DEFINE_SPINLOCK(io_tlb_lock);
106 
107 static int late_alloc;
108 
109 static int __init
110 setup_io_tlb_npages(char *str)
111 {
112 	if (isdigit(*str)) {
113 		io_tlb_nslabs = simple_strtoul(str, &str, 0);
114 		/* avoid tail segment of size < IO_TLB_SEGSIZE */
115 		io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
116 	}
117 	if (*str == ',')
118 		++str;
119 	if (!strcmp(str, "force")) {
120 		swiotlb_force = SWIOTLB_FORCE;
121 	} else if (!strcmp(str, "noforce")) {
122 		swiotlb_force = SWIOTLB_NO_FORCE;
123 		io_tlb_nslabs = 1;
124 	}
125 
126 	return 0;
127 }
128 early_param("swiotlb", setup_io_tlb_npages);
129 /* make io_tlb_overflow tunable too? */
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 	vaddr = phys_to_virt(io_tlb_overflow_buffer);
199 	bytes = PAGE_ALIGN(io_tlb_overflow);
200 	set_memory_decrypted((unsigned long)vaddr, bytes >> PAGE_SHIFT);
201 	memset(vaddr, 0, bytes);
202 }
203 
204 int __init swiotlb_init_with_tbl(char *tlb, unsigned long nslabs, int verbose)
205 {
206 	void *v_overflow_buffer;
207 	unsigned long i, bytes;
208 
209 	bytes = nslabs << IO_TLB_SHIFT;
210 
211 	io_tlb_nslabs = nslabs;
212 	io_tlb_start = __pa(tlb);
213 	io_tlb_end = io_tlb_start + bytes;
214 
215 	/*
216 	 * Get the overflow emergency buffer
217 	 */
218 	v_overflow_buffer = memblock_virt_alloc_low_nopanic(
219 						PAGE_ALIGN(io_tlb_overflow),
220 						PAGE_SIZE);
221 	if (!v_overflow_buffer)
222 		return -ENOMEM;
223 
224 	io_tlb_overflow_buffer = __pa(v_overflow_buffer);
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 	io_tlb_list = memblock_virt_alloc(
232 				PAGE_ALIGN(io_tlb_nslabs * sizeof(int)),
233 				PAGE_SIZE);
234 	io_tlb_orig_addr = memblock_virt_alloc(
235 				PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)),
236 				PAGE_SIZE);
237 	for (i = 0; i < io_tlb_nslabs; i++) {
238 		io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE);
239 		io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
240 	}
241 	io_tlb_index = 0;
242 
243 	if (verbose)
244 		swiotlb_print_info();
245 
246 	swiotlb_set_max_segment(io_tlb_nslabs << IO_TLB_SHIFT);
247 	return 0;
248 }
249 
250 /*
251  * Statically reserve bounce buffer space and initialize bounce buffer data
252  * structures for the software IO TLB used to implement the DMA API.
253  */
254 void  __init
255 swiotlb_init(int verbose)
256 {
257 	size_t default_size = IO_TLB_DEFAULT_SIZE;
258 	unsigned char *vstart;
259 	unsigned long bytes;
260 
261 	if (!io_tlb_nslabs) {
262 		io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
263 		io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
264 	}
265 
266 	bytes = io_tlb_nslabs << IO_TLB_SHIFT;
267 
268 	/* Get IO TLB memory from the low pages */
269 	vstart = memblock_virt_alloc_low_nopanic(PAGE_ALIGN(bytes), PAGE_SIZE);
270 	if (vstart && !swiotlb_init_with_tbl(vstart, io_tlb_nslabs, verbose))
271 		return;
272 
273 	if (io_tlb_start)
274 		memblock_free_early(io_tlb_start,
275 				    PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
276 	pr_warn("Cannot allocate buffer");
277 	no_iotlb_memory = true;
278 }
279 
280 /*
281  * Systems with larger DMA zones (those that don't support ISA) can
282  * initialize the swiotlb later using the slab allocator if needed.
283  * This should be just like above, but with some error catching.
284  */
285 int
286 swiotlb_late_init_with_default_size(size_t default_size)
287 {
288 	unsigned long bytes, req_nslabs = io_tlb_nslabs;
289 	unsigned char *vstart = NULL;
290 	unsigned int order;
291 	int rc = 0;
292 
293 	if (!io_tlb_nslabs) {
294 		io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
295 		io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
296 	}
297 
298 	/*
299 	 * Get IO TLB memory from the low pages
300 	 */
301 	order = get_order(io_tlb_nslabs << IO_TLB_SHIFT);
302 	io_tlb_nslabs = SLABS_PER_PAGE << order;
303 	bytes = io_tlb_nslabs << IO_TLB_SHIFT;
304 
305 	while ((SLABS_PER_PAGE << order) > IO_TLB_MIN_SLABS) {
306 		vstart = (void *)__get_free_pages(GFP_DMA | __GFP_NOWARN,
307 						  order);
308 		if (vstart)
309 			break;
310 		order--;
311 	}
312 
313 	if (!vstart) {
314 		io_tlb_nslabs = req_nslabs;
315 		return -ENOMEM;
316 	}
317 	if (order != get_order(bytes)) {
318 		pr_warn("only able to allocate %ld MB\n",
319 			(PAGE_SIZE << order) >> 20);
320 		io_tlb_nslabs = SLABS_PER_PAGE << order;
321 	}
322 	rc = swiotlb_late_init_with_tbl(vstart, io_tlb_nslabs);
323 	if (rc)
324 		free_pages((unsigned long)vstart, order);
325 
326 	return rc;
327 }
328 
329 int
330 swiotlb_late_init_with_tbl(char *tlb, unsigned long nslabs)
331 {
332 	unsigned long i, bytes;
333 	unsigned char *v_overflow_buffer;
334 
335 	bytes = nslabs << IO_TLB_SHIFT;
336 
337 	io_tlb_nslabs = nslabs;
338 	io_tlb_start = virt_to_phys(tlb);
339 	io_tlb_end = io_tlb_start + bytes;
340 
341 	set_memory_decrypted((unsigned long)tlb, bytes >> PAGE_SHIFT);
342 	memset(tlb, 0, bytes);
343 
344 	/*
345 	 * Get the overflow emergency buffer
346 	 */
347 	v_overflow_buffer = (void *)__get_free_pages(GFP_DMA,
348 						     get_order(io_tlb_overflow));
349 	if (!v_overflow_buffer)
350 		goto cleanup2;
351 
352 	set_memory_decrypted((unsigned long)v_overflow_buffer,
353 			io_tlb_overflow >> PAGE_SHIFT);
354 	memset(v_overflow_buffer, 0, io_tlb_overflow);
355 	io_tlb_overflow_buffer = virt_to_phys(v_overflow_buffer);
356 
357 	/*
358 	 * Allocate and initialize the free list array.  This array is used
359 	 * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
360 	 * between io_tlb_start and io_tlb_end.
361 	 */
362 	io_tlb_list = (unsigned int *)__get_free_pages(GFP_KERNEL,
363 	                              get_order(io_tlb_nslabs * sizeof(int)));
364 	if (!io_tlb_list)
365 		goto cleanup3;
366 
367 	io_tlb_orig_addr = (phys_addr_t *)
368 		__get_free_pages(GFP_KERNEL,
369 				 get_order(io_tlb_nslabs *
370 					   sizeof(phys_addr_t)));
371 	if (!io_tlb_orig_addr)
372 		goto cleanup4;
373 
374 	for (i = 0; i < io_tlb_nslabs; i++) {
375 		io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE);
376 		io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
377 	}
378 	io_tlb_index = 0;
379 
380 	swiotlb_print_info();
381 
382 	late_alloc = 1;
383 
384 	swiotlb_set_max_segment(io_tlb_nslabs << IO_TLB_SHIFT);
385 
386 	return 0;
387 
388 cleanup4:
389 	free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
390 	                                                 sizeof(int)));
391 	io_tlb_list = NULL;
392 cleanup3:
393 	free_pages((unsigned long)v_overflow_buffer,
394 		   get_order(io_tlb_overflow));
395 	io_tlb_overflow_buffer = 0;
396 cleanup2:
397 	io_tlb_end = 0;
398 	io_tlb_start = 0;
399 	io_tlb_nslabs = 0;
400 	max_segment = 0;
401 	return -ENOMEM;
402 }
403 
404 void __init swiotlb_exit(void)
405 {
406 	if (!io_tlb_orig_addr)
407 		return;
408 
409 	if (late_alloc) {
410 		free_pages((unsigned long)phys_to_virt(io_tlb_overflow_buffer),
411 			   get_order(io_tlb_overflow));
412 		free_pages((unsigned long)io_tlb_orig_addr,
413 			   get_order(io_tlb_nslabs * sizeof(phys_addr_t)));
414 		free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
415 								 sizeof(int)));
416 		free_pages((unsigned long)phys_to_virt(io_tlb_start),
417 			   get_order(io_tlb_nslabs << IO_TLB_SHIFT));
418 	} else {
419 		memblock_free_late(io_tlb_overflow_buffer,
420 				   PAGE_ALIGN(io_tlb_overflow));
421 		memblock_free_late(__pa(io_tlb_orig_addr),
422 				   PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)));
423 		memblock_free_late(__pa(io_tlb_list),
424 				   PAGE_ALIGN(io_tlb_nslabs * sizeof(int)));
425 		memblock_free_late(io_tlb_start,
426 				   PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
427 	}
428 	io_tlb_nslabs = 0;
429 	max_segment = 0;
430 }
431 
432 int is_swiotlb_buffer(phys_addr_t paddr)
433 {
434 	return paddr >= io_tlb_start && paddr < io_tlb_end;
435 }
436 
437 /*
438  * Bounce: copy the swiotlb buffer back to the original dma location
439  */
440 static void swiotlb_bounce(phys_addr_t orig_addr, phys_addr_t tlb_addr,
441 			   size_t size, enum dma_data_direction dir)
442 {
443 	unsigned long pfn = PFN_DOWN(orig_addr);
444 	unsigned char *vaddr = phys_to_virt(tlb_addr);
445 
446 	if (PageHighMem(pfn_to_page(pfn))) {
447 		/* The buffer does not have a mapping.  Map it in and copy */
448 		unsigned int offset = orig_addr & ~PAGE_MASK;
449 		char *buffer;
450 		unsigned int sz = 0;
451 		unsigned long flags;
452 
453 		while (size) {
454 			sz = min_t(size_t, PAGE_SIZE - offset, size);
455 
456 			local_irq_save(flags);
457 			buffer = kmap_atomic(pfn_to_page(pfn));
458 			if (dir == DMA_TO_DEVICE)
459 				memcpy(vaddr, buffer + offset, sz);
460 			else
461 				memcpy(buffer + offset, vaddr, sz);
462 			kunmap_atomic(buffer);
463 			local_irq_restore(flags);
464 
465 			size -= sz;
466 			pfn++;
467 			vaddr += sz;
468 			offset = 0;
469 		}
470 	} else if (dir == DMA_TO_DEVICE) {
471 		memcpy(vaddr, phys_to_virt(orig_addr), size);
472 	} else {
473 		memcpy(phys_to_virt(orig_addr), vaddr, size);
474 	}
475 }
476 
477 phys_addr_t swiotlb_tbl_map_single(struct device *hwdev,
478 				   dma_addr_t tbl_dma_addr,
479 				   phys_addr_t orig_addr, size_t size,
480 				   enum dma_data_direction dir,
481 				   unsigned long attrs)
482 {
483 	unsigned long flags;
484 	phys_addr_t tlb_addr;
485 	unsigned int nslots, stride, index, wrap;
486 	int i;
487 	unsigned long mask;
488 	unsigned long offset_slots;
489 	unsigned long max_slots;
490 
491 	if (no_iotlb_memory)
492 		panic("Can not allocate SWIOTLB buffer earlier and can't now provide you with the DMA bounce buffer");
493 
494 	if (mem_encrypt_active())
495 		pr_warn_once("%s is active and system is using DMA bounce buffers\n",
496 			     sme_active() ? "SME" : "SEV");
497 
498 	mask = dma_get_seg_boundary(hwdev);
499 
500 	tbl_dma_addr &= mask;
501 
502 	offset_slots = ALIGN(tbl_dma_addr, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
503 
504 	/*
505  	 * Carefully handle integer overflow which can occur when mask == ~0UL.
506  	 */
507 	max_slots = mask + 1
508 		    ? ALIGN(mask + 1, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT
509 		    : 1UL << (BITS_PER_LONG - IO_TLB_SHIFT);
510 
511 	/*
512 	 * For mappings greater than or equal to a page, we limit the stride
513 	 * (and hence alignment) to a page size.
514 	 */
515 	nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
516 	if (size >= PAGE_SIZE)
517 		stride = (1 << (PAGE_SHIFT - IO_TLB_SHIFT));
518 	else
519 		stride = 1;
520 
521 	BUG_ON(!nslots);
522 
523 	/*
524 	 * Find suitable number of IO TLB entries size that will fit this
525 	 * request and allocate a buffer from that IO TLB pool.
526 	 */
527 	spin_lock_irqsave(&io_tlb_lock, flags);
528 	index = ALIGN(io_tlb_index, stride);
529 	if (index >= io_tlb_nslabs)
530 		index = 0;
531 	wrap = index;
532 
533 	do {
534 		while (iommu_is_span_boundary(index, nslots, offset_slots,
535 					      max_slots)) {
536 			index += stride;
537 			if (index >= io_tlb_nslabs)
538 				index = 0;
539 			if (index == wrap)
540 				goto not_found;
541 		}
542 
543 		/*
544 		 * If we find a slot that indicates we have 'nslots' number of
545 		 * contiguous buffers, we allocate the buffers from that slot
546 		 * and mark the entries as '0' indicating unavailable.
547 		 */
548 		if (io_tlb_list[index] >= nslots) {
549 			int count = 0;
550 
551 			for (i = index; i < (int) (index + nslots); i++)
552 				io_tlb_list[i] = 0;
553 			for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE - 1) && io_tlb_list[i]; i--)
554 				io_tlb_list[i] = ++count;
555 			tlb_addr = io_tlb_start + (index << IO_TLB_SHIFT);
556 
557 			/*
558 			 * Update the indices to avoid searching in the next
559 			 * round.
560 			 */
561 			io_tlb_index = ((index + nslots) < io_tlb_nslabs
562 					? (index + nslots) : 0);
563 
564 			goto found;
565 		}
566 		index += stride;
567 		if (index >= io_tlb_nslabs)
568 			index = 0;
569 	} while (index != wrap);
570 
571 not_found:
572 	spin_unlock_irqrestore(&io_tlb_lock, flags);
573 	if (!(attrs & DMA_ATTR_NO_WARN) && printk_ratelimit())
574 		dev_warn(hwdev, "swiotlb buffer is full (sz: %zd bytes)\n", size);
575 	return SWIOTLB_MAP_ERROR;
576 found:
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, size, DMA_TO_DEVICE);
589 
590 	return tlb_addr;
591 }
592 
593 /*
594  * Allocates bounce buffer and returns its physical address.
595  */
596 static phys_addr_t
597 map_single(struct device *hwdev, phys_addr_t phys, size_t size,
598 	   enum dma_data_direction dir, unsigned long attrs)
599 {
600 	dma_addr_t start_dma_addr;
601 
602 	if (swiotlb_force == SWIOTLB_NO_FORCE) {
603 		dev_warn_ratelimited(hwdev, "Cannot do DMA to address %pa\n",
604 				     &phys);
605 		return SWIOTLB_MAP_ERROR;
606 	}
607 
608 	start_dma_addr = __phys_to_dma(hwdev, io_tlb_start);
609 	return swiotlb_tbl_map_single(hwdev, start_dma_addr, phys, size,
610 				      dir, attrs);
611 }
612 
613 /*
614  * tlb_addr is the physical address of the bounce buffer to unmap.
615  */
616 void swiotlb_tbl_unmap_single(struct device *hwdev, phys_addr_t tlb_addr,
617 			      size_t size, enum dma_data_direction dir,
618 			      unsigned long attrs)
619 {
620 	unsigned long flags;
621 	int i, count, nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
622 	int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT;
623 	phys_addr_t orig_addr = io_tlb_orig_addr[index];
624 
625 	/*
626 	 * First, sync the memory before unmapping the entry
627 	 */
628 	if (orig_addr != INVALID_PHYS_ADDR &&
629 	    !(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
630 	    ((dir == DMA_FROM_DEVICE) || (dir == DMA_BIDIRECTIONAL)))
631 		swiotlb_bounce(orig_addr, tlb_addr, size, DMA_FROM_DEVICE);
632 
633 	/*
634 	 * Return the buffer to the free list by setting the corresponding
635 	 * entries to indicate the number of contiguous entries available.
636 	 * While returning the entries to the free list, we merge the entries
637 	 * with slots below and above the pool being returned.
638 	 */
639 	spin_lock_irqsave(&io_tlb_lock, flags);
640 	{
641 		count = ((index + nslots) < ALIGN(index + 1, IO_TLB_SEGSIZE) ?
642 			 io_tlb_list[index + nslots] : 0);
643 		/*
644 		 * Step 1: return the slots to the free list, merging the
645 		 * slots with superceeding slots
646 		 */
647 		for (i = index + nslots - 1; i >= index; i--) {
648 			io_tlb_list[i] = ++count;
649 			io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
650 		}
651 		/*
652 		 * Step 2: merge the returned slots with the preceding slots,
653 		 * if available (non zero)
654 		 */
655 		for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE -1) && io_tlb_list[i]; i--)
656 			io_tlb_list[i] = ++count;
657 	}
658 	spin_unlock_irqrestore(&io_tlb_lock, flags);
659 }
660 
661 void swiotlb_tbl_sync_single(struct device *hwdev, phys_addr_t tlb_addr,
662 			     size_t size, enum dma_data_direction dir,
663 			     enum dma_sync_target target)
664 {
665 	int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT;
666 	phys_addr_t orig_addr = io_tlb_orig_addr[index];
667 
668 	if (orig_addr == INVALID_PHYS_ADDR)
669 		return;
670 	orig_addr += (unsigned long)tlb_addr & ((1 << IO_TLB_SHIFT) - 1);
671 
672 	switch (target) {
673 	case SYNC_FOR_CPU:
674 		if (likely(dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL))
675 			swiotlb_bounce(orig_addr, tlb_addr,
676 				       size, DMA_FROM_DEVICE);
677 		else
678 			BUG_ON(dir != DMA_TO_DEVICE);
679 		break;
680 	case SYNC_FOR_DEVICE:
681 		if (likely(dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL))
682 			swiotlb_bounce(orig_addr, tlb_addr,
683 				       size, DMA_TO_DEVICE);
684 		else
685 			BUG_ON(dir != DMA_FROM_DEVICE);
686 		break;
687 	default:
688 		BUG();
689 	}
690 }
691 
692 static inline bool dma_coherent_ok(struct device *dev, dma_addr_t addr,
693 		size_t size)
694 {
695 	u64 mask = DMA_BIT_MASK(32);
696 
697 	if (dev && dev->coherent_dma_mask)
698 		mask = dev->coherent_dma_mask;
699 	return addr + size - 1 <= mask;
700 }
701 
702 static void *
703 swiotlb_alloc_buffer(struct device *dev, size_t size, dma_addr_t *dma_handle,
704 		unsigned long attrs)
705 {
706 	phys_addr_t phys_addr;
707 
708 	if (swiotlb_force == SWIOTLB_NO_FORCE)
709 		goto out_warn;
710 
711 	phys_addr = swiotlb_tbl_map_single(dev,
712 			__phys_to_dma(dev, io_tlb_start),
713 			0, size, DMA_FROM_DEVICE, attrs);
714 	if (phys_addr == SWIOTLB_MAP_ERROR)
715 		goto out_warn;
716 
717 	*dma_handle = __phys_to_dma(dev, phys_addr);
718 	if (!dma_coherent_ok(dev, *dma_handle, size))
719 		goto out_unmap;
720 
721 	memset(phys_to_virt(phys_addr), 0, size);
722 	return phys_to_virt(phys_addr);
723 
724 out_unmap:
725 	dev_warn(dev, "hwdev DMA mask = 0x%016Lx, dev_addr = 0x%016Lx\n",
726 		(unsigned long long)dev->coherent_dma_mask,
727 		(unsigned long long)*dma_handle);
728 
729 	/*
730 	 * DMA_TO_DEVICE to avoid memcpy in unmap_single.
731 	 * DMA_ATTR_SKIP_CPU_SYNC is optional.
732 	 */
733 	swiotlb_tbl_unmap_single(dev, phys_addr, size, DMA_TO_DEVICE,
734 			DMA_ATTR_SKIP_CPU_SYNC);
735 out_warn:
736 	if (!(attrs & DMA_ATTR_NO_WARN) && printk_ratelimit()) {
737 		dev_warn(dev,
738 			"swiotlb: coherent allocation failed, size=%zu\n",
739 			size);
740 		dump_stack();
741 	}
742 	return NULL;
743 }
744 
745 static bool swiotlb_free_buffer(struct device *dev, size_t size,
746 		dma_addr_t dma_addr)
747 {
748 	phys_addr_t phys_addr = dma_to_phys(dev, dma_addr);
749 
750 	WARN_ON_ONCE(irqs_disabled());
751 
752 	if (!is_swiotlb_buffer(phys_addr))
753 		return false;
754 
755 	/*
756 	 * DMA_TO_DEVICE to avoid memcpy in swiotlb_tbl_unmap_single.
757 	 * DMA_ATTR_SKIP_CPU_SYNC is optional.
758 	 */
759 	swiotlb_tbl_unmap_single(dev, phys_addr, size, DMA_TO_DEVICE,
760 				 DMA_ATTR_SKIP_CPU_SYNC);
761 	return true;
762 }
763 
764 static void
765 swiotlb_full(struct device *dev, size_t size, enum dma_data_direction dir,
766 	     int do_panic)
767 {
768 	if (swiotlb_force == SWIOTLB_NO_FORCE)
769 		return;
770 
771 	/*
772 	 * Ran out of IOMMU space for this operation. This is very bad.
773 	 * Unfortunately the drivers cannot handle this operation properly.
774 	 * unless they check for dma_mapping_error (most don't)
775 	 * When the mapping is small enough return a static buffer to limit
776 	 * the damage, or panic when the transfer is too big.
777 	 */
778 	dev_err_ratelimited(dev, "DMA: Out of SW-IOMMU space for %zu bytes\n",
779 			    size);
780 
781 	if (size <= io_tlb_overflow || !do_panic)
782 		return;
783 
784 	if (dir == DMA_BIDIRECTIONAL)
785 		panic("DMA: Random memory could be DMA accessed\n");
786 	if (dir == DMA_FROM_DEVICE)
787 		panic("DMA: Random memory could be DMA written\n");
788 	if (dir == DMA_TO_DEVICE)
789 		panic("DMA: Random memory could be DMA read\n");
790 }
791 
792 /*
793  * Map a single buffer of the indicated size for DMA in streaming mode.  The
794  * physical address to use is returned.
795  *
796  * Once the device is given the dma address, the device owns this memory until
797  * either swiotlb_unmap_page or swiotlb_dma_sync_single is performed.
798  */
799 dma_addr_t swiotlb_map_page(struct device *dev, struct page *page,
800 			    unsigned long offset, size_t size,
801 			    enum dma_data_direction dir,
802 			    unsigned long attrs)
803 {
804 	phys_addr_t map, phys = page_to_phys(page) + offset;
805 	dma_addr_t dev_addr = phys_to_dma(dev, phys);
806 
807 	BUG_ON(dir == DMA_NONE);
808 	/*
809 	 * If the address happens to be in the device's DMA window,
810 	 * we can safely return the device addr and not worry about bounce
811 	 * buffering it.
812 	 */
813 	if (dma_capable(dev, dev_addr, size) && swiotlb_force != SWIOTLB_FORCE)
814 		return dev_addr;
815 
816 	trace_swiotlb_bounced(dev, dev_addr, size, swiotlb_force);
817 
818 	/* Oh well, have to allocate and map a bounce buffer. */
819 	map = map_single(dev, phys, size, dir, attrs);
820 	if (map == SWIOTLB_MAP_ERROR) {
821 		swiotlb_full(dev, size, dir, 1);
822 		return __phys_to_dma(dev, io_tlb_overflow_buffer);
823 	}
824 
825 	dev_addr = __phys_to_dma(dev, map);
826 
827 	/* Ensure that the address returned is DMA'ble */
828 	if (dma_capable(dev, dev_addr, size))
829 		return dev_addr;
830 
831 	attrs |= DMA_ATTR_SKIP_CPU_SYNC;
832 	swiotlb_tbl_unmap_single(dev, map, size, dir, attrs);
833 
834 	return __phys_to_dma(dev, io_tlb_overflow_buffer);
835 }
836 
837 /*
838  * Unmap a single streaming mode DMA translation.  The dma_addr and size must
839  * match what was provided for in a previous swiotlb_map_page call.  All
840  * other usages are undefined.
841  *
842  * After this call, reads by the cpu to the buffer are guaranteed to see
843  * whatever the device wrote there.
844  */
845 static void unmap_single(struct device *hwdev, dma_addr_t dev_addr,
846 			 size_t size, enum dma_data_direction dir,
847 			 unsigned long attrs)
848 {
849 	phys_addr_t paddr = dma_to_phys(hwdev, dev_addr);
850 
851 	BUG_ON(dir == DMA_NONE);
852 
853 	if (is_swiotlb_buffer(paddr)) {
854 		swiotlb_tbl_unmap_single(hwdev, paddr, size, dir, attrs);
855 		return;
856 	}
857 
858 	if (dir != DMA_FROM_DEVICE)
859 		return;
860 
861 	/*
862 	 * phys_to_virt doesn't work with hihgmem page but we could
863 	 * call dma_mark_clean() with hihgmem page here. However, we
864 	 * are fine since dma_mark_clean() is null on POWERPC. We can
865 	 * make dma_mark_clean() take a physical address if necessary.
866 	 */
867 	dma_mark_clean(phys_to_virt(paddr), size);
868 }
869 
870 void swiotlb_unmap_page(struct device *hwdev, dma_addr_t dev_addr,
871 			size_t size, enum dma_data_direction dir,
872 			unsigned long attrs)
873 {
874 	unmap_single(hwdev, dev_addr, size, dir, attrs);
875 }
876 
877 /*
878  * Make physical memory consistent for a single streaming mode DMA translation
879  * after a transfer.
880  *
881  * If you perform a swiotlb_map_page() but wish to interrogate the buffer
882  * using the cpu, yet do not wish to teardown the dma mapping, you must
883  * call this function before doing so.  At the next point you give the dma
884  * address back to the card, you must first perform a
885  * swiotlb_dma_sync_for_device, and then the device again owns the buffer
886  */
887 static void
888 swiotlb_sync_single(struct device *hwdev, dma_addr_t dev_addr,
889 		    size_t size, enum dma_data_direction dir,
890 		    enum dma_sync_target target)
891 {
892 	phys_addr_t paddr = dma_to_phys(hwdev, dev_addr);
893 
894 	BUG_ON(dir == DMA_NONE);
895 
896 	if (is_swiotlb_buffer(paddr)) {
897 		swiotlb_tbl_sync_single(hwdev, paddr, size, dir, target);
898 		return;
899 	}
900 
901 	if (dir != DMA_FROM_DEVICE)
902 		return;
903 
904 	dma_mark_clean(phys_to_virt(paddr), size);
905 }
906 
907 void
908 swiotlb_sync_single_for_cpu(struct device *hwdev, dma_addr_t dev_addr,
909 			    size_t size, enum dma_data_direction dir)
910 {
911 	swiotlb_sync_single(hwdev, dev_addr, size, dir, SYNC_FOR_CPU);
912 }
913 
914 void
915 swiotlb_sync_single_for_device(struct device *hwdev, dma_addr_t dev_addr,
916 			       size_t size, enum dma_data_direction dir)
917 {
918 	swiotlb_sync_single(hwdev, dev_addr, size, dir, SYNC_FOR_DEVICE);
919 }
920 
921 /*
922  * Map a set of buffers described by scatterlist in streaming mode for DMA.
923  * This is the scatter-gather version of the above swiotlb_map_page
924  * interface.  Here the scatter gather list elements are each tagged with the
925  * appropriate dma address and length.  They are obtained via
926  * sg_dma_{address,length}(SG).
927  *
928  * NOTE: An implementation may be able to use a smaller number of
929  *       DMA address/length pairs than there are SG table elements.
930  *       (for example via virtual mapping capabilities)
931  *       The routine returns the number of addr/length pairs actually
932  *       used, at most nents.
933  *
934  * Device ownership issues as mentioned above for swiotlb_map_page are the
935  * same here.
936  */
937 int
938 swiotlb_map_sg_attrs(struct device *hwdev, struct scatterlist *sgl, int nelems,
939 		     enum dma_data_direction dir, unsigned long attrs)
940 {
941 	struct scatterlist *sg;
942 	int i;
943 
944 	BUG_ON(dir == DMA_NONE);
945 
946 	for_each_sg(sgl, sg, nelems, i) {
947 		phys_addr_t paddr = sg_phys(sg);
948 		dma_addr_t dev_addr = phys_to_dma(hwdev, paddr);
949 
950 		if (swiotlb_force == SWIOTLB_FORCE ||
951 		    !dma_capable(hwdev, dev_addr, sg->length)) {
952 			phys_addr_t map = map_single(hwdev, sg_phys(sg),
953 						     sg->length, dir, attrs);
954 			if (map == SWIOTLB_MAP_ERROR) {
955 				/* Don't panic here, we expect map_sg users
956 				   to do proper error handling. */
957 				swiotlb_full(hwdev, sg->length, dir, 0);
958 				attrs |= DMA_ATTR_SKIP_CPU_SYNC;
959 				swiotlb_unmap_sg_attrs(hwdev, sgl, i, dir,
960 						       attrs);
961 				sg_dma_len(sgl) = 0;
962 				return 0;
963 			}
964 			sg->dma_address = __phys_to_dma(hwdev, map);
965 		} else
966 			sg->dma_address = dev_addr;
967 		sg_dma_len(sg) = sg->length;
968 	}
969 	return nelems;
970 }
971 
972 /*
973  * Unmap a set of streaming mode DMA translations.  Again, cpu read rules
974  * concerning calls here are the same as for swiotlb_unmap_page() above.
975  */
976 void
977 swiotlb_unmap_sg_attrs(struct device *hwdev, struct scatterlist *sgl,
978 		       int nelems, enum dma_data_direction dir,
979 		       unsigned long attrs)
980 {
981 	struct scatterlist *sg;
982 	int i;
983 
984 	BUG_ON(dir == DMA_NONE);
985 
986 	for_each_sg(sgl, sg, nelems, i)
987 		unmap_single(hwdev, sg->dma_address, sg_dma_len(sg), dir,
988 			     attrs);
989 }
990 
991 /*
992  * Make physical memory consistent for a set of streaming mode DMA translations
993  * after a transfer.
994  *
995  * The same as swiotlb_sync_single_* but for a scatter-gather list, same rules
996  * and usage.
997  */
998 static void
999 swiotlb_sync_sg(struct device *hwdev, struct scatterlist *sgl,
1000 		int nelems, enum dma_data_direction dir,
1001 		enum dma_sync_target target)
1002 {
1003 	struct scatterlist *sg;
1004 	int i;
1005 
1006 	for_each_sg(sgl, sg, nelems, i)
1007 		swiotlb_sync_single(hwdev, sg->dma_address,
1008 				    sg_dma_len(sg), dir, target);
1009 }
1010 
1011 void
1012 swiotlb_sync_sg_for_cpu(struct device *hwdev, struct scatterlist *sg,
1013 			int nelems, enum dma_data_direction dir)
1014 {
1015 	swiotlb_sync_sg(hwdev, sg, nelems, dir, SYNC_FOR_CPU);
1016 }
1017 
1018 void
1019 swiotlb_sync_sg_for_device(struct device *hwdev, struct scatterlist *sg,
1020 			   int nelems, enum dma_data_direction dir)
1021 {
1022 	swiotlb_sync_sg(hwdev, sg, nelems, dir, SYNC_FOR_DEVICE);
1023 }
1024 
1025 int
1026 swiotlb_dma_mapping_error(struct device *hwdev, dma_addr_t dma_addr)
1027 {
1028 	return (dma_addr == __phys_to_dma(hwdev, io_tlb_overflow_buffer));
1029 }
1030 
1031 /*
1032  * Return whether the given device DMA address mask can be supported
1033  * properly.  For example, if your device can only drive the low 24-bits
1034  * during bus mastering, then you would pass 0x00ffffff as the mask to
1035  * this function.
1036  */
1037 int
1038 swiotlb_dma_supported(struct device *hwdev, u64 mask)
1039 {
1040 	return __phys_to_dma(hwdev, io_tlb_end - 1) <= mask;
1041 }
1042 
1043 void *swiotlb_alloc(struct device *dev, size_t size, dma_addr_t *dma_handle,
1044 		gfp_t gfp, unsigned long attrs)
1045 {
1046 	void *vaddr;
1047 
1048 	/* temporary workaround: */
1049 	if (gfp & __GFP_NOWARN)
1050 		attrs |= DMA_ATTR_NO_WARN;
1051 
1052 	/*
1053 	 * Don't print a warning when the first allocation attempt fails.
1054 	 * swiotlb_alloc_coherent() will print a warning when the DMA memory
1055 	 * allocation ultimately failed.
1056 	 */
1057 	gfp |= __GFP_NOWARN;
1058 
1059 	vaddr = dma_direct_alloc(dev, size, dma_handle, gfp, attrs);
1060 	if (!vaddr)
1061 		vaddr = swiotlb_alloc_buffer(dev, size, dma_handle, attrs);
1062 	return vaddr;
1063 }
1064 
1065 void swiotlb_free(struct device *dev, size_t size, void *vaddr,
1066 		dma_addr_t dma_addr, unsigned long attrs)
1067 {
1068 	if (!swiotlb_free_buffer(dev, size, dma_addr))
1069 		dma_direct_free(dev, size, vaddr, dma_addr, attrs);
1070 }
1071 
1072 const struct dma_map_ops swiotlb_dma_ops = {
1073 	.mapping_error		= swiotlb_dma_mapping_error,
1074 	.alloc			= swiotlb_alloc,
1075 	.free			= swiotlb_free,
1076 	.sync_single_for_cpu	= swiotlb_sync_single_for_cpu,
1077 	.sync_single_for_device	= swiotlb_sync_single_for_device,
1078 	.sync_sg_for_cpu	= swiotlb_sync_sg_for_cpu,
1079 	.sync_sg_for_device	= swiotlb_sync_sg_for_device,
1080 	.map_sg			= swiotlb_map_sg_attrs,
1081 	.unmap_sg		= swiotlb_unmap_sg_attrs,
1082 	.map_page		= swiotlb_map_page,
1083 	.unmap_page		= swiotlb_unmap_page,
1084 	.dma_supported		= dma_direct_supported,
1085 };
1086 EXPORT_SYMBOL(swiotlb_dma_ops);
1087