xref: /openbmc/linux/kernel/dma/swiotlb.c (revision 5d331b7f)
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/dma-noncoherent.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 
39 #include <asm/io.h>
40 #include <asm/dma.h>
41 
42 #include <linux/init.h>
43 #include <linux/memblock.h>
44 #include <linux/iommu-helper.h>
45 
46 #define CREATE_TRACE_POINTS
47 #include <trace/events/swiotlb.h>
48 
49 #define OFFSET(val,align) ((unsigned long)	\
50 	                   ( (val) & ( (align) - 1)))
51 
52 #define SLABS_PER_PAGE (1 << (PAGE_SHIFT - IO_TLB_SHIFT))
53 
54 /*
55  * Minimum IO TLB size to bother booting with.  Systems with mainly
56  * 64bit capable cards will only lightly use the swiotlb.  If we can't
57  * allocate a contiguous 1MB, we're probably in trouble anyway.
58  */
59 #define IO_TLB_MIN_SLABS ((1<<20) >> IO_TLB_SHIFT)
60 
61 enum swiotlb_force swiotlb_force;
62 
63 /*
64  * Used to do a quick range check in swiotlb_tbl_unmap_single and
65  * swiotlb_tbl_sync_single_*, to see if the memory was in fact allocated by this
66  * API.
67  */
68 static phys_addr_t io_tlb_start, io_tlb_end;
69 
70 /*
71  * The number of IO TLB blocks (in groups of 64) between io_tlb_start and
72  * io_tlb_end.  This is command line adjustable via setup_io_tlb_npages.
73  */
74 static unsigned long io_tlb_nslabs;
75 
76 /*
77  * This is a free list describing the number of free entries available from
78  * each index
79  */
80 static unsigned int *io_tlb_list;
81 static unsigned int io_tlb_index;
82 
83 /*
84  * Max segment that we can provide which (if pages are contingous) will
85  * not be bounced (unless SWIOTLB_FORCE is set).
86  */
87 unsigned int max_segment;
88 
89 /*
90  * We need to save away the original address corresponding to a mapped entry
91  * for the sync operations.
92  */
93 #define INVALID_PHYS_ADDR (~(phys_addr_t)0)
94 static phys_addr_t *io_tlb_orig_addr;
95 
96 /*
97  * Protect the above data structures in the map and unmap calls
98  */
99 static DEFINE_SPINLOCK(io_tlb_lock);
100 
101 static int late_alloc;
102 
103 static int __init
104 setup_io_tlb_npages(char *str)
105 {
106 	if (isdigit(*str)) {
107 		io_tlb_nslabs = simple_strtoul(str, &str, 0);
108 		/* avoid tail segment of size < IO_TLB_SEGSIZE */
109 		io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
110 	}
111 	if (*str == ',')
112 		++str;
113 	if (!strcmp(str, "force")) {
114 		swiotlb_force = SWIOTLB_FORCE;
115 	} else if (!strcmp(str, "noforce")) {
116 		swiotlb_force = SWIOTLB_NO_FORCE;
117 		io_tlb_nslabs = 1;
118 	}
119 
120 	return 0;
121 }
122 early_param("swiotlb", setup_io_tlb_npages);
123 
124 unsigned long swiotlb_nr_tbl(void)
125 {
126 	return io_tlb_nslabs;
127 }
128 EXPORT_SYMBOL_GPL(swiotlb_nr_tbl);
129 
130 unsigned int swiotlb_max_segment(void)
131 {
132 	return max_segment;
133 }
134 EXPORT_SYMBOL_GPL(swiotlb_max_segment);
135 
136 void swiotlb_set_max_segment(unsigned int val)
137 {
138 	if (swiotlb_force == SWIOTLB_FORCE)
139 		max_segment = 1;
140 	else
141 		max_segment = rounddown(val, PAGE_SIZE);
142 }
143 
144 /* default to 64MB */
145 #define IO_TLB_DEFAULT_SIZE (64UL<<20)
146 unsigned long swiotlb_size_or_default(void)
147 {
148 	unsigned long size;
149 
150 	size = io_tlb_nslabs << IO_TLB_SHIFT;
151 
152 	return size ? size : (IO_TLB_DEFAULT_SIZE);
153 }
154 
155 static bool no_iotlb_memory;
156 
157 void swiotlb_print_info(void)
158 {
159 	unsigned long bytes = io_tlb_nslabs << IO_TLB_SHIFT;
160 
161 	if (no_iotlb_memory) {
162 		pr_warn("No low mem\n");
163 		return;
164 	}
165 
166 	pr_info("mapped [mem %#010llx-%#010llx] (%luMB)\n",
167 	       (unsigned long long)io_tlb_start,
168 	       (unsigned long long)io_tlb_end,
169 	       bytes >> 20);
170 }
171 
172 /*
173  * Early SWIOTLB allocation may be too early to allow an architecture to
174  * perform the desired operations.  This function allows the architecture to
175  * call SWIOTLB when the operations are possible.  It needs to be called
176  * before the SWIOTLB memory is used.
177  */
178 void __init swiotlb_update_mem_attributes(void)
179 {
180 	void *vaddr;
181 	unsigned long bytes;
182 
183 	if (no_iotlb_memory || late_alloc)
184 		return;
185 
186 	vaddr = phys_to_virt(io_tlb_start);
187 	bytes = PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT);
188 	set_memory_decrypted((unsigned long)vaddr, bytes >> PAGE_SHIFT);
189 	memset(vaddr, 0, bytes);
190 }
191 
192 int __init swiotlb_init_with_tbl(char *tlb, unsigned long nslabs, int verbose)
193 {
194 	unsigned long i, bytes;
195 
196 	bytes = nslabs << IO_TLB_SHIFT;
197 
198 	io_tlb_nslabs = nslabs;
199 	io_tlb_start = __pa(tlb);
200 	io_tlb_end = io_tlb_start + bytes;
201 
202 	/*
203 	 * Allocate and initialize the free list array.  This array is used
204 	 * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
205 	 * between io_tlb_start and io_tlb_end.
206 	 */
207 	io_tlb_list = memblock_alloc(
208 				PAGE_ALIGN(io_tlb_nslabs * sizeof(int)),
209 				PAGE_SIZE);
210 	io_tlb_orig_addr = memblock_alloc(
211 				PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)),
212 				PAGE_SIZE);
213 	for (i = 0; i < io_tlb_nslabs; i++) {
214 		io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE);
215 		io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
216 	}
217 	io_tlb_index = 0;
218 
219 	if (verbose)
220 		swiotlb_print_info();
221 
222 	swiotlb_set_max_segment(io_tlb_nslabs << IO_TLB_SHIFT);
223 	return 0;
224 }
225 
226 /*
227  * Statically reserve bounce buffer space and initialize bounce buffer data
228  * structures for the software IO TLB used to implement the DMA API.
229  */
230 void  __init
231 swiotlb_init(int verbose)
232 {
233 	size_t default_size = IO_TLB_DEFAULT_SIZE;
234 	unsigned char *vstart;
235 	unsigned long bytes;
236 
237 	if (!io_tlb_nslabs) {
238 		io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
239 		io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
240 	}
241 
242 	bytes = io_tlb_nslabs << IO_TLB_SHIFT;
243 
244 	/* Get IO TLB memory from the low pages */
245 	vstart = memblock_alloc_low_nopanic(PAGE_ALIGN(bytes), PAGE_SIZE);
246 	if (vstart && !swiotlb_init_with_tbl(vstart, io_tlb_nslabs, verbose))
247 		return;
248 
249 	if (io_tlb_start)
250 		memblock_free_early(io_tlb_start,
251 				    PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
252 	pr_warn("Cannot allocate buffer");
253 	no_iotlb_memory = true;
254 }
255 
256 /*
257  * Systems with larger DMA zones (those that don't support ISA) can
258  * initialize the swiotlb later using the slab allocator if needed.
259  * This should be just like above, but with some error catching.
260  */
261 int
262 swiotlb_late_init_with_default_size(size_t default_size)
263 {
264 	unsigned long bytes, req_nslabs = io_tlb_nslabs;
265 	unsigned char *vstart = NULL;
266 	unsigned int order;
267 	int rc = 0;
268 
269 	if (!io_tlb_nslabs) {
270 		io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
271 		io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
272 	}
273 
274 	/*
275 	 * Get IO TLB memory from the low pages
276 	 */
277 	order = get_order(io_tlb_nslabs << IO_TLB_SHIFT);
278 	io_tlb_nslabs = SLABS_PER_PAGE << order;
279 	bytes = io_tlb_nslabs << IO_TLB_SHIFT;
280 
281 	while ((SLABS_PER_PAGE << order) > IO_TLB_MIN_SLABS) {
282 		vstart = (void *)__get_free_pages(GFP_DMA | __GFP_NOWARN,
283 						  order);
284 		if (vstart)
285 			break;
286 		order--;
287 	}
288 
289 	if (!vstart) {
290 		io_tlb_nslabs = req_nslabs;
291 		return -ENOMEM;
292 	}
293 	if (order != get_order(bytes)) {
294 		pr_warn("only able to allocate %ld MB\n",
295 			(PAGE_SIZE << order) >> 20);
296 		io_tlb_nslabs = SLABS_PER_PAGE << order;
297 	}
298 	rc = swiotlb_late_init_with_tbl(vstart, io_tlb_nslabs);
299 	if (rc)
300 		free_pages((unsigned long)vstart, order);
301 
302 	return rc;
303 }
304 
305 int
306 swiotlb_late_init_with_tbl(char *tlb, unsigned long nslabs)
307 {
308 	unsigned long i, bytes;
309 
310 	bytes = nslabs << IO_TLB_SHIFT;
311 
312 	io_tlb_nslabs = nslabs;
313 	io_tlb_start = virt_to_phys(tlb);
314 	io_tlb_end = io_tlb_start + bytes;
315 
316 	set_memory_decrypted((unsigned long)tlb, bytes >> PAGE_SHIFT);
317 	memset(tlb, 0, bytes);
318 
319 	/*
320 	 * Allocate and initialize the free list array.  This array is used
321 	 * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
322 	 * between io_tlb_start and io_tlb_end.
323 	 */
324 	io_tlb_list = (unsigned int *)__get_free_pages(GFP_KERNEL,
325 	                              get_order(io_tlb_nslabs * sizeof(int)));
326 	if (!io_tlb_list)
327 		goto cleanup3;
328 
329 	io_tlb_orig_addr = (phys_addr_t *)
330 		__get_free_pages(GFP_KERNEL,
331 				 get_order(io_tlb_nslabs *
332 					   sizeof(phys_addr_t)));
333 	if (!io_tlb_orig_addr)
334 		goto cleanup4;
335 
336 	for (i = 0; i < io_tlb_nslabs; i++) {
337 		io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE);
338 		io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
339 	}
340 	io_tlb_index = 0;
341 
342 	swiotlb_print_info();
343 
344 	late_alloc = 1;
345 
346 	swiotlb_set_max_segment(io_tlb_nslabs << IO_TLB_SHIFT);
347 
348 	return 0;
349 
350 cleanup4:
351 	free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
352 	                                                 sizeof(int)));
353 	io_tlb_list = NULL;
354 cleanup3:
355 	io_tlb_end = 0;
356 	io_tlb_start = 0;
357 	io_tlb_nslabs = 0;
358 	max_segment = 0;
359 	return -ENOMEM;
360 }
361 
362 void __init swiotlb_exit(void)
363 {
364 	if (!io_tlb_orig_addr)
365 		return;
366 
367 	if (late_alloc) {
368 		free_pages((unsigned long)io_tlb_orig_addr,
369 			   get_order(io_tlb_nslabs * sizeof(phys_addr_t)));
370 		free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
371 								 sizeof(int)));
372 		free_pages((unsigned long)phys_to_virt(io_tlb_start),
373 			   get_order(io_tlb_nslabs << IO_TLB_SHIFT));
374 	} else {
375 		memblock_free_late(__pa(io_tlb_orig_addr),
376 				   PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)));
377 		memblock_free_late(__pa(io_tlb_list),
378 				   PAGE_ALIGN(io_tlb_nslabs * sizeof(int)));
379 		memblock_free_late(io_tlb_start,
380 				   PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
381 	}
382 	io_tlb_nslabs = 0;
383 	max_segment = 0;
384 }
385 
386 static int is_swiotlb_buffer(phys_addr_t paddr)
387 {
388 	return paddr >= io_tlb_start && paddr < io_tlb_end;
389 }
390 
391 /*
392  * Bounce: copy the swiotlb buffer back to the original dma location
393  */
394 static void swiotlb_bounce(phys_addr_t orig_addr, phys_addr_t tlb_addr,
395 			   size_t size, enum dma_data_direction dir)
396 {
397 	unsigned long pfn = PFN_DOWN(orig_addr);
398 	unsigned char *vaddr = phys_to_virt(tlb_addr);
399 
400 	if (PageHighMem(pfn_to_page(pfn))) {
401 		/* The buffer does not have a mapping.  Map it in and copy */
402 		unsigned int offset = orig_addr & ~PAGE_MASK;
403 		char *buffer;
404 		unsigned int sz = 0;
405 		unsigned long flags;
406 
407 		while (size) {
408 			sz = min_t(size_t, PAGE_SIZE - offset, size);
409 
410 			local_irq_save(flags);
411 			buffer = kmap_atomic(pfn_to_page(pfn));
412 			if (dir == DMA_TO_DEVICE)
413 				memcpy(vaddr, buffer + offset, sz);
414 			else
415 				memcpy(buffer + offset, vaddr, sz);
416 			kunmap_atomic(buffer);
417 			local_irq_restore(flags);
418 
419 			size -= sz;
420 			pfn++;
421 			vaddr += sz;
422 			offset = 0;
423 		}
424 	} else if (dir == DMA_TO_DEVICE) {
425 		memcpy(vaddr, phys_to_virt(orig_addr), size);
426 	} else {
427 		memcpy(phys_to_virt(orig_addr), vaddr, size);
428 	}
429 }
430 
431 phys_addr_t swiotlb_tbl_map_single(struct device *hwdev,
432 				   dma_addr_t tbl_dma_addr,
433 				   phys_addr_t orig_addr, size_t size,
434 				   enum dma_data_direction dir,
435 				   unsigned long attrs)
436 {
437 	unsigned long flags;
438 	phys_addr_t tlb_addr;
439 	unsigned int nslots, stride, index, wrap;
440 	int i;
441 	unsigned long mask;
442 	unsigned long offset_slots;
443 	unsigned long max_slots;
444 
445 	if (no_iotlb_memory)
446 		panic("Can not allocate SWIOTLB buffer earlier and can't now provide you with the DMA bounce buffer");
447 
448 	if (mem_encrypt_active())
449 		pr_warn_once("%s is active and system is using DMA bounce buffers\n",
450 			     sme_active() ? "SME" : "SEV");
451 
452 	mask = dma_get_seg_boundary(hwdev);
453 
454 	tbl_dma_addr &= mask;
455 
456 	offset_slots = ALIGN(tbl_dma_addr, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
457 
458 	/*
459  	 * Carefully handle integer overflow which can occur when mask == ~0UL.
460  	 */
461 	max_slots = mask + 1
462 		    ? ALIGN(mask + 1, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT
463 		    : 1UL << (BITS_PER_LONG - IO_TLB_SHIFT);
464 
465 	/*
466 	 * For mappings greater than or equal to a page, we limit the stride
467 	 * (and hence alignment) to a page size.
468 	 */
469 	nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
470 	if (size >= PAGE_SIZE)
471 		stride = (1 << (PAGE_SHIFT - IO_TLB_SHIFT));
472 	else
473 		stride = 1;
474 
475 	BUG_ON(!nslots);
476 
477 	/*
478 	 * Find suitable number of IO TLB entries size that will fit this
479 	 * request and allocate a buffer from that IO TLB pool.
480 	 */
481 	spin_lock_irqsave(&io_tlb_lock, flags);
482 	index = ALIGN(io_tlb_index, stride);
483 	if (index >= io_tlb_nslabs)
484 		index = 0;
485 	wrap = index;
486 
487 	do {
488 		while (iommu_is_span_boundary(index, nslots, offset_slots,
489 					      max_slots)) {
490 			index += stride;
491 			if (index >= io_tlb_nslabs)
492 				index = 0;
493 			if (index == wrap)
494 				goto not_found;
495 		}
496 
497 		/*
498 		 * If we find a slot that indicates we have 'nslots' number of
499 		 * contiguous buffers, we allocate the buffers from that slot
500 		 * and mark the entries as '0' indicating unavailable.
501 		 */
502 		if (io_tlb_list[index] >= nslots) {
503 			int count = 0;
504 
505 			for (i = index; i < (int) (index + nslots); i++)
506 				io_tlb_list[i] = 0;
507 			for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE - 1) && io_tlb_list[i]; i--)
508 				io_tlb_list[i] = ++count;
509 			tlb_addr = io_tlb_start + (index << IO_TLB_SHIFT);
510 
511 			/*
512 			 * Update the indices to avoid searching in the next
513 			 * round.
514 			 */
515 			io_tlb_index = ((index + nslots) < io_tlb_nslabs
516 					? (index + nslots) : 0);
517 
518 			goto found;
519 		}
520 		index += stride;
521 		if (index >= io_tlb_nslabs)
522 			index = 0;
523 	} while (index != wrap);
524 
525 not_found:
526 	spin_unlock_irqrestore(&io_tlb_lock, flags);
527 	if (!(attrs & DMA_ATTR_NO_WARN) && printk_ratelimit())
528 		dev_warn(hwdev, "swiotlb buffer is full (sz: %zd bytes)\n", size);
529 	return SWIOTLB_MAP_ERROR;
530 found:
531 	spin_unlock_irqrestore(&io_tlb_lock, flags);
532 
533 	/*
534 	 * Save away the mapping from the original address to the DMA address.
535 	 * This is needed when we sync the memory.  Then we sync the buffer if
536 	 * needed.
537 	 */
538 	for (i = 0; i < nslots; i++)
539 		io_tlb_orig_addr[index+i] = orig_addr + (i << IO_TLB_SHIFT);
540 	if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
541 	    (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL))
542 		swiotlb_bounce(orig_addr, tlb_addr, size, DMA_TO_DEVICE);
543 
544 	return tlb_addr;
545 }
546 
547 /*
548  * tlb_addr is the physical address of the bounce buffer to unmap.
549  */
550 void swiotlb_tbl_unmap_single(struct device *hwdev, phys_addr_t tlb_addr,
551 			      size_t size, enum dma_data_direction dir,
552 			      unsigned long attrs)
553 {
554 	unsigned long flags;
555 	int i, count, nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
556 	int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT;
557 	phys_addr_t orig_addr = io_tlb_orig_addr[index];
558 
559 	/*
560 	 * First, sync the memory before unmapping the entry
561 	 */
562 	if (orig_addr != INVALID_PHYS_ADDR &&
563 	    !(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
564 	    ((dir == DMA_FROM_DEVICE) || (dir == DMA_BIDIRECTIONAL)))
565 		swiotlb_bounce(orig_addr, tlb_addr, size, DMA_FROM_DEVICE);
566 
567 	/*
568 	 * Return the buffer to the free list by setting the corresponding
569 	 * entries to indicate the number of contiguous entries available.
570 	 * While returning the entries to the free list, we merge the entries
571 	 * with slots below and above the pool being returned.
572 	 */
573 	spin_lock_irqsave(&io_tlb_lock, flags);
574 	{
575 		count = ((index + nslots) < ALIGN(index + 1, IO_TLB_SEGSIZE) ?
576 			 io_tlb_list[index + nslots] : 0);
577 		/*
578 		 * Step 1: return the slots to the free list, merging the
579 		 * slots with superceeding slots
580 		 */
581 		for (i = index + nslots - 1; i >= index; i--) {
582 			io_tlb_list[i] = ++count;
583 			io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
584 		}
585 		/*
586 		 * Step 2: merge the returned slots with the preceding slots,
587 		 * if available (non zero)
588 		 */
589 		for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE -1) && io_tlb_list[i]; i--)
590 			io_tlb_list[i] = ++count;
591 	}
592 	spin_unlock_irqrestore(&io_tlb_lock, flags);
593 }
594 
595 void swiotlb_tbl_sync_single(struct device *hwdev, phys_addr_t tlb_addr,
596 			     size_t size, enum dma_data_direction dir,
597 			     enum dma_sync_target target)
598 {
599 	int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT;
600 	phys_addr_t orig_addr = io_tlb_orig_addr[index];
601 
602 	if (orig_addr == INVALID_PHYS_ADDR)
603 		return;
604 	orig_addr += (unsigned long)tlb_addr & ((1 << IO_TLB_SHIFT) - 1);
605 
606 	switch (target) {
607 	case SYNC_FOR_CPU:
608 		if (likely(dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL))
609 			swiotlb_bounce(orig_addr, tlb_addr,
610 				       size, DMA_FROM_DEVICE);
611 		else
612 			BUG_ON(dir != DMA_TO_DEVICE);
613 		break;
614 	case SYNC_FOR_DEVICE:
615 		if (likely(dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL))
616 			swiotlb_bounce(orig_addr, tlb_addr,
617 				       size, DMA_TO_DEVICE);
618 		else
619 			BUG_ON(dir != DMA_FROM_DEVICE);
620 		break;
621 	default:
622 		BUG();
623 	}
624 }
625 
626 static dma_addr_t swiotlb_bounce_page(struct device *dev, phys_addr_t *phys,
627 		size_t size, enum dma_data_direction dir, unsigned long attrs)
628 {
629 	dma_addr_t dma_addr;
630 
631 	if (unlikely(swiotlb_force == SWIOTLB_NO_FORCE)) {
632 		dev_warn_ratelimited(dev,
633 			"Cannot do DMA to address %pa\n", phys);
634 		return DIRECT_MAPPING_ERROR;
635 	}
636 
637 	/* Oh well, have to allocate and map a bounce buffer. */
638 	*phys = swiotlb_tbl_map_single(dev, __phys_to_dma(dev, io_tlb_start),
639 			*phys, size, dir, attrs);
640 	if (*phys == SWIOTLB_MAP_ERROR)
641 		return DIRECT_MAPPING_ERROR;
642 
643 	/* Ensure that the address returned is DMA'ble */
644 	dma_addr = __phys_to_dma(dev, *phys);
645 	if (unlikely(!dma_capable(dev, dma_addr, size))) {
646 		swiotlb_tbl_unmap_single(dev, *phys, size, dir,
647 			attrs | DMA_ATTR_SKIP_CPU_SYNC);
648 		return DIRECT_MAPPING_ERROR;
649 	}
650 
651 	return dma_addr;
652 }
653 
654 /*
655  * Map a single buffer of the indicated size for DMA in streaming mode.  The
656  * physical address to use is returned.
657  *
658  * Once the device is given the dma address, the device owns this memory until
659  * either swiotlb_unmap_page or swiotlb_dma_sync_single is performed.
660  */
661 dma_addr_t swiotlb_map_page(struct device *dev, struct page *page,
662 			    unsigned long offset, size_t size,
663 			    enum dma_data_direction dir,
664 			    unsigned long attrs)
665 {
666 	phys_addr_t phys = page_to_phys(page) + offset;
667 	dma_addr_t dev_addr = phys_to_dma(dev, phys);
668 
669 	BUG_ON(dir == DMA_NONE);
670 	/*
671 	 * If the address happens to be in the device's DMA window,
672 	 * we can safely return the device addr and not worry about bounce
673 	 * buffering it.
674 	 */
675 	if (!dma_capable(dev, dev_addr, size) ||
676 	    swiotlb_force == SWIOTLB_FORCE) {
677 		trace_swiotlb_bounced(dev, dev_addr, size, swiotlb_force);
678 		dev_addr = swiotlb_bounce_page(dev, &phys, size, dir, attrs);
679 	}
680 
681 	if (!dev_is_dma_coherent(dev) &&
682 	    (attrs & DMA_ATTR_SKIP_CPU_SYNC) == 0)
683 		arch_sync_dma_for_device(dev, phys, size, dir);
684 
685 	return dev_addr;
686 }
687 
688 /*
689  * Unmap a single streaming mode DMA translation.  The dma_addr and size must
690  * match what was provided for in a previous swiotlb_map_page call.  All
691  * other usages are undefined.
692  *
693  * After this call, reads by the cpu to the buffer are guaranteed to see
694  * whatever the device wrote there.
695  */
696 void swiotlb_unmap_page(struct device *hwdev, dma_addr_t dev_addr,
697 			size_t size, enum dma_data_direction dir,
698 			unsigned long attrs)
699 {
700 	phys_addr_t paddr = dma_to_phys(hwdev, dev_addr);
701 
702 	BUG_ON(dir == DMA_NONE);
703 
704 	if (!dev_is_dma_coherent(hwdev) &&
705 	    (attrs & DMA_ATTR_SKIP_CPU_SYNC) == 0)
706 		arch_sync_dma_for_cpu(hwdev, paddr, size, dir);
707 
708 	if (is_swiotlb_buffer(paddr)) {
709 		swiotlb_tbl_unmap_single(hwdev, paddr, size, dir, attrs);
710 		return;
711 	}
712 
713 	if (dir != DMA_FROM_DEVICE)
714 		return;
715 
716 	/*
717 	 * phys_to_virt doesn't work with hihgmem page but we could
718 	 * call dma_mark_clean() with hihgmem page here. However, we
719 	 * are fine since dma_mark_clean() is null on POWERPC. We can
720 	 * make dma_mark_clean() take a physical address if necessary.
721 	 */
722 	dma_mark_clean(phys_to_virt(paddr), size);
723 }
724 
725 /*
726  * Make physical memory consistent for a single streaming mode DMA translation
727  * after a transfer.
728  *
729  * If you perform a swiotlb_map_page() but wish to interrogate the buffer
730  * using the cpu, yet do not wish to teardown the dma mapping, you must
731  * call this function before doing so.  At the next point you give the dma
732  * address back to the card, you must first perform a
733  * swiotlb_dma_sync_for_device, and then the device again owns the buffer
734  */
735 static void
736 swiotlb_sync_single(struct device *hwdev, dma_addr_t dev_addr,
737 		    size_t size, enum dma_data_direction dir,
738 		    enum dma_sync_target target)
739 {
740 	phys_addr_t paddr = dma_to_phys(hwdev, dev_addr);
741 
742 	BUG_ON(dir == DMA_NONE);
743 
744 	if (!dev_is_dma_coherent(hwdev) && target == SYNC_FOR_CPU)
745 		arch_sync_dma_for_cpu(hwdev, paddr, size, dir);
746 
747 	if (is_swiotlb_buffer(paddr))
748 		swiotlb_tbl_sync_single(hwdev, paddr, size, dir, target);
749 
750 	if (!dev_is_dma_coherent(hwdev) && target == SYNC_FOR_DEVICE)
751 		arch_sync_dma_for_device(hwdev, paddr, size, dir);
752 
753 	if (!is_swiotlb_buffer(paddr) && dir == DMA_FROM_DEVICE)
754 		dma_mark_clean(phys_to_virt(paddr), size);
755 }
756 
757 void
758 swiotlb_sync_single_for_cpu(struct device *hwdev, dma_addr_t dev_addr,
759 			    size_t size, enum dma_data_direction dir)
760 {
761 	swiotlb_sync_single(hwdev, dev_addr, size, dir, SYNC_FOR_CPU);
762 }
763 
764 void
765 swiotlb_sync_single_for_device(struct device *hwdev, dma_addr_t dev_addr,
766 			       size_t size, enum dma_data_direction dir)
767 {
768 	swiotlb_sync_single(hwdev, dev_addr, size, dir, SYNC_FOR_DEVICE);
769 }
770 
771 /*
772  * Map a set of buffers described by scatterlist in streaming mode for DMA.
773  * This is the scatter-gather version of the above swiotlb_map_page
774  * interface.  Here the scatter gather list elements are each tagged with the
775  * appropriate dma address and length.  They are obtained via
776  * sg_dma_{address,length}(SG).
777  *
778  * Device ownership issues as mentioned above for swiotlb_map_page are the
779  * same here.
780  */
781 int
782 swiotlb_map_sg_attrs(struct device *dev, struct scatterlist *sgl, int nelems,
783 		     enum dma_data_direction dir, unsigned long attrs)
784 {
785 	struct scatterlist *sg;
786 	int i;
787 
788 	for_each_sg(sgl, sg, nelems, i) {
789 		sg->dma_address = swiotlb_map_page(dev, sg_page(sg), sg->offset,
790 				sg->length, dir, attrs);
791 		if (sg->dma_address == DIRECT_MAPPING_ERROR)
792 			goto out_error;
793 		sg_dma_len(sg) = sg->length;
794 	}
795 
796 	return nelems;
797 
798 out_error:
799 	swiotlb_unmap_sg_attrs(dev, sgl, i, dir,
800 			attrs | DMA_ATTR_SKIP_CPU_SYNC);
801 	sg_dma_len(sgl) = 0;
802 	return 0;
803 }
804 
805 /*
806  * Unmap a set of streaming mode DMA translations.  Again, cpu read rules
807  * concerning calls here are the same as for swiotlb_unmap_page() above.
808  */
809 void
810 swiotlb_unmap_sg_attrs(struct device *hwdev, struct scatterlist *sgl,
811 		       int nelems, enum dma_data_direction dir,
812 		       unsigned long attrs)
813 {
814 	struct scatterlist *sg;
815 	int i;
816 
817 	BUG_ON(dir == DMA_NONE);
818 
819 	for_each_sg(sgl, sg, nelems, i)
820 		swiotlb_unmap_page(hwdev, sg->dma_address, sg_dma_len(sg), dir,
821 			     attrs);
822 }
823 
824 /*
825  * Make physical memory consistent for a set of streaming mode DMA translations
826  * after a transfer.
827  *
828  * The same as swiotlb_sync_single_* but for a scatter-gather list, same rules
829  * and usage.
830  */
831 static void
832 swiotlb_sync_sg(struct device *hwdev, struct scatterlist *sgl,
833 		int nelems, enum dma_data_direction dir,
834 		enum dma_sync_target target)
835 {
836 	struct scatterlist *sg;
837 	int i;
838 
839 	for_each_sg(sgl, sg, nelems, i)
840 		swiotlb_sync_single(hwdev, sg->dma_address,
841 				    sg_dma_len(sg), dir, target);
842 }
843 
844 void
845 swiotlb_sync_sg_for_cpu(struct device *hwdev, struct scatterlist *sg,
846 			int nelems, enum dma_data_direction dir)
847 {
848 	swiotlb_sync_sg(hwdev, sg, nelems, dir, SYNC_FOR_CPU);
849 }
850 
851 void
852 swiotlb_sync_sg_for_device(struct device *hwdev, struct scatterlist *sg,
853 			   int nelems, enum dma_data_direction dir)
854 {
855 	swiotlb_sync_sg(hwdev, sg, nelems, dir, SYNC_FOR_DEVICE);
856 }
857 
858 /*
859  * Return whether the given device DMA address mask can be supported
860  * properly.  For example, if your device can only drive the low 24-bits
861  * during bus mastering, then you would pass 0x00ffffff as the mask to
862  * this function.
863  */
864 int
865 swiotlb_dma_supported(struct device *hwdev, u64 mask)
866 {
867 	return __phys_to_dma(hwdev, io_tlb_end - 1) <= mask;
868 }
869 
870 const struct dma_map_ops swiotlb_dma_ops = {
871 	.mapping_error		= dma_direct_mapping_error,
872 	.alloc			= dma_direct_alloc,
873 	.free			= dma_direct_free,
874 	.sync_single_for_cpu	= swiotlb_sync_single_for_cpu,
875 	.sync_single_for_device	= swiotlb_sync_single_for_device,
876 	.sync_sg_for_cpu	= swiotlb_sync_sg_for_cpu,
877 	.sync_sg_for_device	= swiotlb_sync_sg_for_device,
878 	.map_sg			= swiotlb_map_sg_attrs,
879 	.unmap_sg		= swiotlb_unmap_sg_attrs,
880 	.map_page		= swiotlb_map_page,
881 	.unmap_page		= swiotlb_unmap_page,
882 	.dma_supported		= dma_direct_supported,
883 };
884 EXPORT_SYMBOL(swiotlb_dma_ops);
885