GNU Linux-libre 5.10.217-gnu1
[releases.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 SLABS_PER_PAGE (1 << (PAGE_SHIFT - IO_TLB_SHIFT))
54
55 /*
56  * Minimum IO TLB size to bother booting with.  Systems with mainly
57  * 64bit capable cards will only lightly use the swiotlb.  If we can't
58  * allocate a contiguous 1MB, we're probably in trouble anyway.
59  */
60 #define IO_TLB_MIN_SLABS ((1<<20) >> IO_TLB_SHIFT)
61
62 enum swiotlb_force swiotlb_force;
63
64 /*
65  * Used to do a quick range check in swiotlb_tbl_unmap_single and
66  * swiotlb_tbl_sync_single_*, to see if the memory was in fact allocated by this
67  * API.
68  */
69 phys_addr_t io_tlb_start, io_tlb_end;
70
71 /*
72  * The number of IO TLB blocks (in groups of 64) between io_tlb_start and
73  * io_tlb_end.  This is command line adjustable via setup_io_tlb_npages.
74  */
75 static unsigned long io_tlb_nslabs;
76
77 /*
78  * The number of used IO TLB block
79  */
80 static unsigned long io_tlb_used;
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 static 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
130 static bool no_iotlb_memory;
131
132 unsigned long swiotlb_nr_tbl(void)
133 {
134         return unlikely(no_iotlb_memory) ? 0 : io_tlb_nslabs;
135 }
136 EXPORT_SYMBOL_GPL(swiotlb_nr_tbl);
137
138 unsigned int swiotlb_max_segment(void)
139 {
140         return unlikely(no_iotlb_memory) ? 0 : max_segment;
141 }
142 EXPORT_SYMBOL_GPL(swiotlb_max_segment);
143
144 void swiotlb_set_max_segment(unsigned int val)
145 {
146         if (swiotlb_force == SWIOTLB_FORCE)
147                 max_segment = 1;
148         else
149                 max_segment = rounddown(val, PAGE_SIZE);
150 }
151
152 /* default to 64MB */
153 #define IO_TLB_DEFAULT_SIZE (64UL<<20)
154 unsigned long swiotlb_size_or_default(void)
155 {
156         unsigned long size;
157
158         size = io_tlb_nslabs << IO_TLB_SHIFT;
159
160         return size ? size : (IO_TLB_DEFAULT_SIZE);
161 }
162
163 void swiotlb_print_info(void)
164 {
165         unsigned long bytes = io_tlb_nslabs << IO_TLB_SHIFT;
166
167         if (no_iotlb_memory) {
168                 pr_warn("No low mem\n");
169                 return;
170         }
171
172         pr_info("mapped [mem %pa-%pa] (%luMB)\n", &io_tlb_start, &io_tlb_end,
173                bytes >> 20);
174 }
175
176 static inline unsigned long io_tlb_offset(unsigned long val)
177 {
178         return val & (IO_TLB_SEGSIZE - 1);
179 }
180
181 static inline unsigned long nr_slots(u64 val)
182 {
183         return DIV_ROUND_UP(val, IO_TLB_SIZE);
184 }
185
186 /*
187  * Early SWIOTLB allocation may be too early to allow an architecture to
188  * perform the desired operations.  This function allows the architecture to
189  * call SWIOTLB when the operations are possible.  It needs to be called
190  * before the SWIOTLB memory is used.
191  */
192 void __init swiotlb_update_mem_attributes(void)
193 {
194         void *vaddr;
195         unsigned long bytes;
196
197         if (no_iotlb_memory || late_alloc)
198                 return;
199
200         vaddr = phys_to_virt(io_tlb_start);
201         bytes = PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT);
202         set_memory_decrypted((unsigned long)vaddr, bytes >> PAGE_SHIFT);
203         memset(vaddr, 0, bytes);
204 }
205
206 int __init swiotlb_init_with_tbl(char *tlb, unsigned long nslabs, int verbose)
207 {
208         unsigned long i, bytes;
209         size_t alloc_size;
210
211         bytes = nslabs << IO_TLB_SHIFT;
212
213         io_tlb_nslabs = nslabs;
214         io_tlb_start = __pa(tlb);
215         io_tlb_end = io_tlb_start + bytes;
216
217         /*
218          * Allocate and initialize the free list array.  This array is used
219          * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
220          * between io_tlb_start and io_tlb_end.
221          */
222         alloc_size = PAGE_ALIGN(io_tlb_nslabs * sizeof(int));
223         io_tlb_list = memblock_alloc(alloc_size, PAGE_SIZE);
224         if (!io_tlb_list)
225                 panic("%s: Failed to allocate %zu bytes align=0x%lx\n",
226                       __func__, alloc_size, PAGE_SIZE);
227
228         alloc_size = PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t));
229         io_tlb_orig_addr = memblock_alloc(alloc_size, PAGE_SIZE);
230         if (!io_tlb_orig_addr)
231                 panic("%s: Failed to allocate %zu bytes align=0x%lx\n",
232                       __func__, alloc_size, PAGE_SIZE);
233
234         for (i = 0; i < io_tlb_nslabs; i++) {
235                 io_tlb_list[i] = IO_TLB_SEGSIZE - io_tlb_offset(i);
236                 io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
237         }
238         io_tlb_index = 0;
239         no_iotlb_memory = false;
240
241         if (verbose)
242                 swiotlb_print_info();
243
244         swiotlb_set_max_segment(io_tlb_nslabs << IO_TLB_SHIFT);
245         return 0;
246 }
247
248 /*
249  * Statically reserve bounce buffer space and initialize bounce buffer data
250  * structures for the software IO TLB used to implement the DMA API.
251  */
252 void  __init
253 swiotlb_init(int verbose)
254 {
255         size_t default_size = IO_TLB_DEFAULT_SIZE;
256         unsigned char *vstart;
257         unsigned long bytes;
258
259         if (!io_tlb_nslabs) {
260                 io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
261                 io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
262         }
263
264         bytes = io_tlb_nslabs << IO_TLB_SHIFT;
265
266         /* Get IO TLB memory from the low pages */
267         vstart = memblock_alloc_low(PAGE_ALIGN(bytes), PAGE_SIZE);
268         if (vstart && !swiotlb_init_with_tbl(vstart, io_tlb_nslabs, verbose))
269                 return;
270
271         if (io_tlb_start) {
272                 memblock_free_early(io_tlb_start,
273                                     PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
274                 io_tlb_start = 0;
275         }
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 static void swiotlb_cleanup(void)
330 {
331         io_tlb_end = 0;
332         io_tlb_start = 0;
333         io_tlb_nslabs = 0;
334         max_segment = 0;
335 }
336
337 int
338 swiotlb_late_init_with_tbl(char *tlb, unsigned long nslabs)
339 {
340         unsigned long i, bytes;
341
342         bytes = nslabs << IO_TLB_SHIFT;
343
344         io_tlb_nslabs = nslabs;
345         io_tlb_start = virt_to_phys(tlb);
346         io_tlb_end = io_tlb_start + bytes;
347
348         set_memory_decrypted((unsigned long)tlb, bytes >> PAGE_SHIFT);
349         memset(tlb, 0, bytes);
350
351         /*
352          * Allocate and initialize the free list array.  This array is used
353          * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
354          * between io_tlb_start and io_tlb_end.
355          */
356         io_tlb_list = (unsigned int *)__get_free_pages(GFP_KERNEL,
357                                       get_order(io_tlb_nslabs * sizeof(int)));
358         if (!io_tlb_list)
359                 goto cleanup3;
360
361         io_tlb_orig_addr = (phys_addr_t *)
362                 __get_free_pages(GFP_KERNEL,
363                                  get_order(io_tlb_nslabs *
364                                            sizeof(phys_addr_t)));
365         if (!io_tlb_orig_addr)
366                 goto cleanup4;
367
368         for (i = 0; i < io_tlb_nslabs; i++) {
369                 io_tlb_list[i] = IO_TLB_SEGSIZE - io_tlb_offset(i);
370                 io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
371         }
372         io_tlb_index = 0;
373         no_iotlb_memory = false;
374
375         swiotlb_print_info();
376
377         late_alloc = 1;
378
379         swiotlb_set_max_segment(io_tlb_nslabs << IO_TLB_SHIFT);
380
381         return 0;
382
383 cleanup4:
384         free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
385                                                          sizeof(int)));
386         io_tlb_list = NULL;
387 cleanup3:
388         swiotlb_cleanup();
389         return -ENOMEM;
390 }
391
392 void __init swiotlb_exit(void)
393 {
394         if (!io_tlb_orig_addr)
395                 return;
396
397         if (late_alloc) {
398                 free_pages((unsigned long)io_tlb_orig_addr,
399                            get_order(io_tlb_nslabs * sizeof(phys_addr_t)));
400                 free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
401                                                                  sizeof(int)));
402                 free_pages((unsigned long)phys_to_virt(io_tlb_start),
403                            get_order(io_tlb_nslabs << IO_TLB_SHIFT));
404         } else {
405                 memblock_free_late(__pa(io_tlb_orig_addr),
406                                    PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)));
407                 memblock_free_late(__pa(io_tlb_list),
408                                    PAGE_ALIGN(io_tlb_nslabs * sizeof(int)));
409                 memblock_free_late(io_tlb_start,
410                                    PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
411         }
412         swiotlb_cleanup();
413 }
414
415 /*
416  * Bounce: copy the swiotlb buffer from or back to the original dma location
417  */
418 static void swiotlb_bounce(phys_addr_t orig_addr, phys_addr_t tlb_addr,
419                            size_t size, enum dma_data_direction dir)
420 {
421         unsigned long pfn = PFN_DOWN(orig_addr);
422         unsigned char *vaddr = phys_to_virt(tlb_addr);
423
424         if (PageHighMem(pfn_to_page(pfn))) {
425                 /* The buffer does not have a mapping.  Map it in and copy */
426                 unsigned int offset = orig_addr & ~PAGE_MASK;
427                 char *buffer;
428                 unsigned int sz = 0;
429                 unsigned long flags;
430
431                 while (size) {
432                         sz = min_t(size_t, PAGE_SIZE - offset, size);
433
434                         local_irq_save(flags);
435                         buffer = kmap_atomic(pfn_to_page(pfn));
436                         if (dir == DMA_TO_DEVICE)
437                                 memcpy(vaddr, buffer + offset, sz);
438                         else
439                                 memcpy(buffer + offset, vaddr, sz);
440                         kunmap_atomic(buffer);
441                         local_irq_restore(flags);
442
443                         size -= sz;
444                         pfn++;
445                         vaddr += sz;
446                         offset = 0;
447                 }
448         } else if (dir == DMA_TO_DEVICE) {
449                 memcpy(vaddr, phys_to_virt(orig_addr), size);
450         } else {
451                 memcpy(phys_to_virt(orig_addr), vaddr, size);
452         }
453 }
454
455 static inline phys_addr_t slot_addr(phys_addr_t start, phys_addr_t idx)
456 {
457         return start + (idx << IO_TLB_SHIFT);
458 }
459
460 /*
461  * Return the offset into a iotlb slot required to keep the device happy.
462  */
463 static unsigned int swiotlb_align_offset(struct device *dev, u64 addr)
464 {
465         return addr & dma_get_min_align_mask(dev) & (IO_TLB_SIZE - 1);
466 }
467
468 /*
469  * Carefully handle integer overflow which can occur when boundary_mask == ~0UL.
470  */
471 static inline unsigned long get_max_slots(unsigned long boundary_mask)
472 {
473         if (boundary_mask == ~0UL)
474                 return 1UL << (BITS_PER_LONG - IO_TLB_SHIFT);
475         return nr_slots(boundary_mask + 1);
476 }
477
478 static unsigned int wrap_index(unsigned int index)
479 {
480         if (index >= io_tlb_nslabs)
481                 return 0;
482         return index;
483 }
484
485 /*
486  * Find a suitable number of IO TLB entries size that will fit this request and
487  * allocate a buffer from that IO TLB pool.
488  */
489 static int find_slots(struct device *dev, phys_addr_t orig_addr,
490                 size_t alloc_size)
491 {
492         unsigned long boundary_mask = dma_get_seg_boundary(dev);
493         dma_addr_t tbl_dma_addr =
494                 phys_to_dma_unencrypted(dev, io_tlb_start) & boundary_mask;
495         unsigned long max_slots = get_max_slots(boundary_mask);
496         unsigned int iotlb_align_mask =
497                 dma_get_min_align_mask(dev) & ~(IO_TLB_SIZE - 1);
498         unsigned int nslots = nr_slots(alloc_size), stride;
499         unsigned int index, wrap, count = 0, i;
500         unsigned long flags;
501
502         BUG_ON(!nslots);
503
504         /*
505          * For mappings with an alignment requirement don't bother looping to
506          * unaligned slots once we found an aligned one.  For allocations of
507          * PAGE_SIZE or larger only look for page aligned allocations.
508          */
509         stride = (iotlb_align_mask >> IO_TLB_SHIFT) + 1;
510         if (alloc_size >= PAGE_SIZE)
511                 stride = max(stride, stride << (PAGE_SHIFT - IO_TLB_SHIFT));
512
513         spin_lock_irqsave(&io_tlb_lock, flags);
514         if (unlikely(nslots > io_tlb_nslabs - io_tlb_used))
515                 goto not_found;
516
517         index = wrap = wrap_index(ALIGN(io_tlb_index, stride));
518         do {
519                 if ((slot_addr(tbl_dma_addr, index) & iotlb_align_mask) !=
520                     (orig_addr & iotlb_align_mask)) {
521                         index = wrap_index(index + 1);
522                         continue;
523                 }
524
525                 /*
526                  * If we find a slot that indicates we have 'nslots' number of
527                  * contiguous buffers, we allocate the buffers from that slot
528                  * and mark the entries as '0' indicating unavailable.
529                  */
530                 if (!iommu_is_span_boundary(index, nslots,
531                                             nr_slots(tbl_dma_addr),
532                                             max_slots)) {
533                         if (io_tlb_list[index] >= nslots)
534                                 goto found;
535                 }
536                 index = wrap_index(index + stride);
537         } while (index != wrap);
538
539 not_found:
540         spin_unlock_irqrestore(&io_tlb_lock, flags);
541         return -1;
542
543 found:
544         for (i = index; i < index + nslots; i++)
545                 io_tlb_list[i] = 0;
546         for (i = index - 1;
547              io_tlb_offset(i) != IO_TLB_SEGSIZE - 1 &&
548              io_tlb_list[i]; i--)
549                 io_tlb_list[i] = ++count;
550
551         /*
552          * Update the indices to avoid searching in the next round.
553          */
554         if (index + nslots < io_tlb_nslabs)
555                 io_tlb_index = index + nslots;
556         else
557                 io_tlb_index = 0;
558         io_tlb_used += nslots;
559
560         spin_unlock_irqrestore(&io_tlb_lock, flags);
561         return index;
562 }
563
564 phys_addr_t swiotlb_tbl_map_single(struct device *dev, phys_addr_t orig_addr,
565                 size_t mapping_size, size_t alloc_size,
566                 enum dma_data_direction dir, unsigned long attrs)
567 {
568         unsigned int offset = swiotlb_align_offset(dev, orig_addr);
569         unsigned int i;
570         int index;
571         phys_addr_t tlb_addr;
572
573         if (no_iotlb_memory)
574                 panic("Can not allocate SWIOTLB buffer earlier and can't now provide you with the DMA bounce buffer");
575
576         if (mem_encrypt_active())
577                 pr_warn_once("Memory encryption is active and system is using DMA bounce buffers\n");
578
579         if (mapping_size > alloc_size) {
580                 dev_warn_once(dev, "Invalid sizes (mapping: %zd bytes, alloc: %zd bytes)",
581                               mapping_size, alloc_size);
582                 return (phys_addr_t)DMA_MAPPING_ERROR;
583         }
584
585         index = find_slots(dev, orig_addr, alloc_size + offset);
586         if (index == -1) {
587                 if (!(attrs & DMA_ATTR_NO_WARN))
588                         dev_warn_ratelimited(dev,
589         "swiotlb buffer is full (sz: %zd bytes), total %lu (slots), used %lu (slots)\n",
590                                  alloc_size, io_tlb_nslabs, io_tlb_used);
591                 return (phys_addr_t)DMA_MAPPING_ERROR;
592         }
593
594         /*
595          * Save away the mapping from the original address to the DMA address.
596          * This is needed when we sync the memory.  Then we sync the buffer if
597          * needed.
598          */
599         for (i = 0; i < nr_slots(alloc_size + offset); i++)
600                 io_tlb_orig_addr[index + i] = slot_addr(orig_addr, i);
601
602         tlb_addr = slot_addr(io_tlb_start, index) + offset;
603         /*
604          * When dir == DMA_FROM_DEVICE we could omit the copy from the orig
605          * to the tlb buffer, if we knew for sure the device will
606          * overwirte the entire current content. But we don't. Thus
607          * unconditional bounce may prevent leaking swiotlb content (i.e.
608          * kernel memory) to user-space.
609          */
610         swiotlb_bounce(orig_addr, tlb_addr, mapping_size, DMA_TO_DEVICE);
611         return tlb_addr;
612 }
613
614 /*
615  * tlb_addr is the physical address of the bounce buffer to unmap.
616  */
617 void swiotlb_tbl_unmap_single(struct device *hwdev, phys_addr_t tlb_addr,
618                               size_t mapping_size, size_t alloc_size,
619                               enum dma_data_direction dir, unsigned long attrs)
620 {
621         unsigned long flags;
622         unsigned int offset = swiotlb_align_offset(hwdev, tlb_addr);
623         int i, count, nslots = nr_slots(alloc_size + offset);
624         int index = (tlb_addr - offset - io_tlb_start) >> IO_TLB_SHIFT;
625         phys_addr_t orig_addr = io_tlb_orig_addr[index];
626
627         /*
628          * First, sync the memory before unmapping the entry
629          */
630         if (orig_addr != INVALID_PHYS_ADDR &&
631             !(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
632             ((dir == DMA_FROM_DEVICE) || (dir == DMA_BIDIRECTIONAL)))
633                 swiotlb_bounce(orig_addr, tlb_addr, mapping_size, DMA_FROM_DEVICE);
634
635         /*
636          * Return the buffer to the free list by setting the corresponding
637          * entries to indicate the number of contiguous entries available.
638          * While returning the entries to the free list, we merge the entries
639          * with slots below and above the pool being returned.
640          */
641         spin_lock_irqsave(&io_tlb_lock, flags);
642         if (index + nslots < ALIGN(index + 1, IO_TLB_SEGSIZE))
643                 count = io_tlb_list[index + nslots];
644         else
645                 count = 0;
646
647         /*
648          * Step 1: return the slots to the free list, merging the slots with
649          * superceeding slots
650          */
651         for (i = index + nslots - 1; i >= index; i--) {
652                 io_tlb_list[i] = ++count;
653                 io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
654         }
655
656         /*
657          * Step 2: merge the returned slots with the preceding slots, if
658          * available (non zero)
659          */
660         for (i = index - 1;
661              io_tlb_offset(i) != IO_TLB_SEGSIZE - 1 && io_tlb_list[i];
662              i--)
663                 io_tlb_list[i] = ++count;
664         io_tlb_used -= nslots;
665         spin_unlock_irqrestore(&io_tlb_lock, flags);
666 }
667
668 void swiotlb_tbl_sync_single(struct device *hwdev, phys_addr_t tlb_addr,
669                              size_t size, enum dma_data_direction dir,
670                              enum dma_sync_target target)
671 {
672         int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT;
673         phys_addr_t orig_addr = io_tlb_orig_addr[index];
674
675         if (orig_addr == INVALID_PHYS_ADDR)
676                 return;
677
678         orig_addr += (tlb_addr & (IO_TLB_SIZE - 1)) -
679                 swiotlb_align_offset(hwdev, orig_addr);
680
681         switch (target) {
682         case SYNC_FOR_CPU:
683                 if (likely(dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL))
684                         swiotlb_bounce(orig_addr, tlb_addr,
685                                        size, DMA_FROM_DEVICE);
686                 else
687                         BUG_ON(dir != DMA_TO_DEVICE);
688                 break;
689         case SYNC_FOR_DEVICE:
690                 if (likely(dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL))
691                         swiotlb_bounce(orig_addr, tlb_addr,
692                                        size, DMA_TO_DEVICE);
693                 else
694                         BUG_ON(dir != DMA_FROM_DEVICE);
695                 break;
696         default:
697                 BUG();
698         }
699 }
700
701 /*
702  * Create a swiotlb mapping for the buffer at @paddr, and in case of DMAing
703  * to the device copy the data into it as well.
704  */
705 dma_addr_t swiotlb_map(struct device *dev, phys_addr_t paddr, size_t size,
706                 enum dma_data_direction dir, unsigned long attrs)
707 {
708         phys_addr_t swiotlb_addr;
709         dma_addr_t dma_addr;
710
711         trace_swiotlb_bounced(dev, phys_to_dma(dev, paddr), size,
712                               swiotlb_force);
713
714         swiotlb_addr = swiotlb_tbl_map_single(dev, paddr, size, size, dir,
715                         attrs);
716         if (swiotlb_addr == (phys_addr_t)DMA_MAPPING_ERROR)
717                 return DMA_MAPPING_ERROR;
718
719         /* Ensure that the address returned is DMA'ble */
720         dma_addr = phys_to_dma_unencrypted(dev, swiotlb_addr);
721         if (unlikely(!dma_capable(dev, dma_addr, size, true))) {
722                 swiotlb_tbl_unmap_single(dev, swiotlb_addr, size, size, dir,
723                         attrs | DMA_ATTR_SKIP_CPU_SYNC);
724                 dev_WARN_ONCE(dev, 1,
725                         "swiotlb addr %pad+%zu overflow (mask %llx, bus limit %llx).\n",
726                         &dma_addr, size, *dev->dma_mask, dev->bus_dma_limit);
727                 return DMA_MAPPING_ERROR;
728         }
729
730         if (!dev_is_dma_coherent(dev) && !(attrs & DMA_ATTR_SKIP_CPU_SYNC))
731                 arch_sync_dma_for_device(swiotlb_addr, size, dir);
732         return dma_addr;
733 }
734
735 size_t swiotlb_max_mapping_size(struct device *dev)
736 {
737         int min_align_mask = dma_get_min_align_mask(dev);
738         int min_align = 0;
739
740         /*
741          * swiotlb_find_slots() skips slots according to
742          * min align mask. This affects max mapping size.
743          * Take it into acount here.
744          */
745         if (min_align_mask)
746                 min_align = roundup(min_align_mask, IO_TLB_SIZE);
747
748         return ((size_t)IO_TLB_SIZE) * IO_TLB_SEGSIZE - min_align;
749 }
750
751 bool is_swiotlb_active(void)
752 {
753         /*
754          * When SWIOTLB is initialized, even if io_tlb_start points to physical
755          * address zero, io_tlb_end surely doesn't.
756          */
757         return io_tlb_end != 0;
758 }
759
760 #ifdef CONFIG_DEBUG_FS
761
762 static int __init swiotlb_create_debugfs(void)
763 {
764         struct dentry *root;
765
766         root = debugfs_create_dir("swiotlb", NULL);
767         debugfs_create_ulong("io_tlb_nslabs", 0400, root, &io_tlb_nslabs);
768         debugfs_create_ulong("io_tlb_used", 0400, root, &io_tlb_used);
769         return 0;
770 }
771
772 late_initcall(swiotlb_create_debugfs);
773
774 #endif