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