swiotlb: move struct io_tlb_slot to swiotlb.c
[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/cc_platform.h>
25 #include <linux/ctype.h>
26 #include <linux/debugfs.h>
27 #include <linux/dma-direct.h>
28 #include <linux/dma-map-ops.h>
29 #include <linux/export.h>
30 #include <linux/gfp.h>
31 #include <linux/highmem.h>
32 #include <linux/io.h>
33 #include <linux/iommu-helper.h>
34 #include <linux/init.h>
35 #include <linux/memblock.h>
36 #include <linux/mm.h>
37 #include <linux/pfn.h>
38 #include <linux/scatterlist.h>
39 #include <linux/set_memory.h>
40 #include <linux/spinlock.h>
41 #include <linux/string.h>
42 #include <linux/swiotlb.h>
43 #include <linux/types.h>
44 #ifdef CONFIG_DMA_RESTRICTED_POOL
45 #include <linux/of.h>
46 #include <linux/of_fdt.h>
47 #include <linux/of_reserved_mem.h>
48 #include <linux/slab.h>
49 #endif
50
51 #define CREATE_TRACE_POINTS
52 #include <trace/events/swiotlb.h>
53
54 #define SLABS_PER_PAGE (1 << (PAGE_SHIFT - IO_TLB_SHIFT))
55
56 /*
57  * Minimum IO TLB size to bother booting with.  Systems with mainly
58  * 64bit capable cards will only lightly use the swiotlb.  If we can't
59  * allocate a contiguous 1MB, we're probably in trouble anyway.
60  */
61 #define IO_TLB_MIN_SLABS ((1<<20) >> IO_TLB_SHIFT)
62
63 #define INVALID_PHYS_ADDR (~(phys_addr_t)0)
64
65 struct io_tlb_slot {
66         phys_addr_t orig_addr;
67         size_t alloc_size;
68         unsigned int list;
69 };
70
71 static bool swiotlb_force_bounce;
72 static bool swiotlb_force_disable;
73
74 struct io_tlb_mem io_tlb_default_mem;
75
76 phys_addr_t swiotlb_unencrypted_base;
77
78 static unsigned long default_nslabs = IO_TLB_DEFAULT_SIZE >> IO_TLB_SHIFT;
79 static unsigned long default_nareas;
80
81 /**
82  * struct io_tlb_area - IO TLB memory area descriptor
83  *
84  * This is a single area with a single lock.
85  *
86  * @used:       The number of used IO TLB block.
87  * @index:      The slot index to start searching in this area for next round.
88  * @lock:       The lock to protect the above data structures in the map and
89  *              unmap calls.
90  */
91 struct io_tlb_area {
92         unsigned long used;
93         unsigned int index;
94         spinlock_t lock;
95 };
96
97 /*
98  * Round up number of slabs to the next power of 2. The last area is going
99  * be smaller than the rest if default_nslabs is not power of two.
100  * The number of slot in an area should be a multiple of IO_TLB_SEGSIZE,
101  * otherwise a segment may span two or more areas. It conflicts with free
102  * contiguous slots tracking: free slots are treated contiguous no matter
103  * whether they cross an area boundary.
104  *
105  * Return true if default_nslabs is rounded up.
106  */
107 static bool round_up_default_nslabs(void)
108 {
109         if (!default_nareas)
110                 return false;
111
112         if (default_nslabs < IO_TLB_SEGSIZE * default_nareas)
113                 default_nslabs = IO_TLB_SEGSIZE * default_nareas;
114         else if (is_power_of_2(default_nslabs))
115                 return false;
116         default_nslabs = roundup_pow_of_two(default_nslabs);
117         return true;
118 }
119
120 static void swiotlb_adjust_nareas(unsigned int nareas)
121 {
122         if (!is_power_of_2(nareas))
123                 nareas = roundup_pow_of_two(nareas);
124
125         default_nareas = nareas;
126
127         pr_info("area num %d.\n", nareas);
128         if (round_up_default_nslabs())
129                 pr_info("SWIOTLB bounce buffer size roundup to %luMB",
130                         (default_nslabs << IO_TLB_SHIFT) >> 20);
131 }
132
133 static int __init
134 setup_io_tlb_npages(char *str)
135 {
136         if (isdigit(*str)) {
137                 /* avoid tail segment of size < IO_TLB_SEGSIZE */
138                 default_nslabs =
139                         ALIGN(simple_strtoul(str, &str, 0), IO_TLB_SEGSIZE);
140         }
141         if (*str == ',')
142                 ++str;
143         if (isdigit(*str))
144                 swiotlb_adjust_nareas(simple_strtoul(str, &str, 0));
145         if (*str == ',')
146                 ++str;
147         if (!strcmp(str, "force"))
148                 swiotlb_force_bounce = true;
149         else if (!strcmp(str, "noforce"))
150                 swiotlb_force_disable = true;
151
152         return 0;
153 }
154 early_param("swiotlb", setup_io_tlb_npages);
155
156 unsigned int swiotlb_max_segment(void)
157 {
158         if (!io_tlb_default_mem.nslabs)
159                 return 0;
160         return rounddown(io_tlb_default_mem.nslabs << IO_TLB_SHIFT, PAGE_SIZE);
161 }
162 EXPORT_SYMBOL_GPL(swiotlb_max_segment);
163
164 unsigned long swiotlb_size_or_default(void)
165 {
166         return default_nslabs << IO_TLB_SHIFT;
167 }
168
169 void __init swiotlb_adjust_size(unsigned long size)
170 {
171         /*
172          * If swiotlb parameter has not been specified, give a chance to
173          * architectures such as those supporting memory encryption to
174          * adjust/expand SWIOTLB size for their use.
175          */
176         if (default_nslabs != IO_TLB_DEFAULT_SIZE >> IO_TLB_SHIFT)
177                 return;
178
179         size = ALIGN(size, IO_TLB_SIZE);
180         default_nslabs = ALIGN(size >> IO_TLB_SHIFT, IO_TLB_SEGSIZE);
181         if (round_up_default_nslabs())
182                 size = default_nslabs << IO_TLB_SHIFT;
183         pr_info("SWIOTLB bounce buffer size adjusted to %luMB", size >> 20);
184 }
185
186 void swiotlb_print_info(void)
187 {
188         struct io_tlb_mem *mem = &io_tlb_default_mem;
189
190         if (!mem->nslabs) {
191                 pr_warn("No low mem\n");
192                 return;
193         }
194
195         pr_info("mapped [mem %pa-%pa] (%luMB)\n", &mem->start, &mem->end,
196                (mem->nslabs << IO_TLB_SHIFT) >> 20);
197 }
198
199 static inline unsigned long io_tlb_offset(unsigned long val)
200 {
201         return val & (IO_TLB_SEGSIZE - 1);
202 }
203
204 static inline unsigned long nr_slots(u64 val)
205 {
206         return DIV_ROUND_UP(val, IO_TLB_SIZE);
207 }
208
209 /*
210  * Remap swioltb memory in the unencrypted physical address space
211  * when swiotlb_unencrypted_base is set. (e.g. for Hyper-V AMD SEV-SNP
212  * Isolation VMs).
213  */
214 #ifdef CONFIG_HAS_IOMEM
215 static void *swiotlb_mem_remap(struct io_tlb_mem *mem, unsigned long bytes)
216 {
217         void *vaddr = NULL;
218
219         if (swiotlb_unencrypted_base) {
220                 phys_addr_t paddr = mem->start + swiotlb_unencrypted_base;
221
222                 vaddr = memremap(paddr, bytes, MEMREMAP_WB);
223                 if (!vaddr)
224                         pr_err("Failed to map the unencrypted memory %pa size %lx.\n",
225                                &paddr, bytes);
226         }
227
228         return vaddr;
229 }
230 #else
231 static void *swiotlb_mem_remap(struct io_tlb_mem *mem, unsigned long bytes)
232 {
233         return NULL;
234 }
235 #endif
236
237 /*
238  * Early SWIOTLB allocation may be too early to allow an architecture to
239  * perform the desired operations.  This function allows the architecture to
240  * call SWIOTLB when the operations are possible.  It needs to be called
241  * before the SWIOTLB memory is used.
242  */
243 void __init swiotlb_update_mem_attributes(void)
244 {
245         struct io_tlb_mem *mem = &io_tlb_default_mem;
246         void *vaddr;
247         unsigned long bytes;
248
249         if (!mem->nslabs || mem->late_alloc)
250                 return;
251         vaddr = phys_to_virt(mem->start);
252         bytes = PAGE_ALIGN(mem->nslabs << IO_TLB_SHIFT);
253         set_memory_decrypted((unsigned long)vaddr, bytes >> PAGE_SHIFT);
254
255         mem->vaddr = swiotlb_mem_remap(mem, bytes);
256         if (!mem->vaddr)
257                 mem->vaddr = vaddr;
258 }
259
260 static void swiotlb_init_io_tlb_mem(struct io_tlb_mem *mem, phys_addr_t start,
261                 unsigned long nslabs, unsigned int flags,
262                 bool late_alloc, unsigned int nareas)
263 {
264         void *vaddr = phys_to_virt(start);
265         unsigned long bytes = nslabs << IO_TLB_SHIFT, i;
266
267         mem->nslabs = nslabs;
268         mem->start = start;
269         mem->end = mem->start + bytes;
270         mem->late_alloc = late_alloc;
271         mem->nareas = nareas;
272         mem->area_nslabs = nslabs / mem->nareas;
273
274         mem->force_bounce = swiotlb_force_bounce || (flags & SWIOTLB_FORCE);
275
276         for (i = 0; i < mem->nareas; i++) {
277                 spin_lock_init(&mem->areas[i].lock);
278                 mem->areas[i].index = 0;
279         }
280
281         for (i = 0; i < mem->nslabs; i++) {
282                 mem->slots[i].list = IO_TLB_SEGSIZE - io_tlb_offset(i);
283                 mem->slots[i].orig_addr = INVALID_PHYS_ADDR;
284                 mem->slots[i].alloc_size = 0;
285         }
286
287         /*
288          * If swiotlb_unencrypted_base is set, the bounce buffer memory will
289          * be remapped and cleared in swiotlb_update_mem_attributes.
290          */
291         if (swiotlb_unencrypted_base)
292                 return;
293
294         memset(vaddr, 0, bytes);
295         mem->vaddr = vaddr;
296         return;
297 }
298
299 /*
300  * Statically reserve bounce buffer space and initialize bounce buffer data
301  * structures for the software IO TLB used to implement the DMA API.
302  */
303 void __init swiotlb_init_remap(bool addressing_limit, unsigned int flags,
304                 int (*remap)(void *tlb, unsigned long nslabs))
305 {
306         struct io_tlb_mem *mem = &io_tlb_default_mem;
307         unsigned long nslabs;
308         size_t alloc_size;
309         size_t bytes;
310         void *tlb;
311
312         if (!addressing_limit && !swiotlb_force_bounce)
313                 return;
314         if (swiotlb_force_disable)
315                 return;
316
317         /*
318          * default_nslabs maybe changed when adjust area number.
319          * So allocate bounce buffer after adjusting area number.
320          */
321         if (!default_nareas)
322                 swiotlb_adjust_nareas(num_possible_cpus());
323
324         nslabs = default_nslabs;
325         if (nslabs < IO_TLB_MIN_SLABS)
326                 panic("%s: nslabs = %lu too small\n", __func__, nslabs);
327
328         /*
329          * By default allocate the bounce buffer memory from low memory, but
330          * allow to pick a location everywhere for hypervisors with guest
331          * memory encryption.
332          */
333 retry:
334         bytes = PAGE_ALIGN(nslabs << IO_TLB_SHIFT);
335         if (flags & SWIOTLB_ANY)
336                 tlb = memblock_alloc(bytes, PAGE_SIZE);
337         else
338                 tlb = memblock_alloc_low(bytes, PAGE_SIZE);
339         if (!tlb) {
340                 pr_warn("%s: Failed to allocate %zu bytes tlb structure\n",
341                         __func__, bytes);
342                 return;
343         }
344
345         if (remap && remap(tlb, nslabs) < 0) {
346                 memblock_free(tlb, PAGE_ALIGN(bytes));
347
348                 nslabs = ALIGN(nslabs >> 1, IO_TLB_SEGSIZE);
349                 if (nslabs < IO_TLB_MIN_SLABS)
350                         panic("%s: Failed to remap %zu bytes\n",
351                               __func__, bytes);
352                 goto retry;
353         }
354
355         alloc_size = PAGE_ALIGN(array_size(sizeof(*mem->slots), nslabs));
356         mem->slots = memblock_alloc(alloc_size, PAGE_SIZE);
357         if (!mem->slots)
358                 panic("%s: Failed to allocate %zu bytes align=0x%lx\n",
359                       __func__, alloc_size, PAGE_SIZE);
360
361         mem->areas = memblock_alloc(sizeof(struct io_tlb_area) *
362                 default_nareas, SMP_CACHE_BYTES);
363         if (!mem->areas)
364                 panic("%s: Failed to allocate mem->areas.\n", __func__);
365
366         swiotlb_init_io_tlb_mem(mem, __pa(tlb), nslabs, flags, false,
367                                 default_nareas);
368
369         if (flags & SWIOTLB_VERBOSE)
370                 swiotlb_print_info();
371 }
372
373 void __init swiotlb_init(bool addressing_limit, unsigned int flags)
374 {
375         swiotlb_init_remap(addressing_limit, flags, NULL);
376 }
377
378 /*
379  * Systems with larger DMA zones (those that don't support ISA) can
380  * initialize the swiotlb later using the slab allocator if needed.
381  * This should be just like above, but with some error catching.
382  */
383 int swiotlb_init_late(size_t size, gfp_t gfp_mask,
384                 int (*remap)(void *tlb, unsigned long nslabs))
385 {
386         struct io_tlb_mem *mem = &io_tlb_default_mem;
387         unsigned long nslabs = ALIGN(size >> IO_TLB_SHIFT, IO_TLB_SEGSIZE);
388         unsigned char *vstart = NULL;
389         unsigned int order, area_order;
390         bool retried = false;
391         int rc = 0;
392
393         if (swiotlb_force_disable)
394                 return 0;
395
396 retry:
397         order = get_order(nslabs << IO_TLB_SHIFT);
398         nslabs = SLABS_PER_PAGE << order;
399
400         while ((SLABS_PER_PAGE << order) > IO_TLB_MIN_SLABS) {
401                 vstart = (void *)__get_free_pages(gfp_mask | __GFP_NOWARN,
402                                                   order);
403                 if (vstart)
404                         break;
405                 order--;
406                 nslabs = SLABS_PER_PAGE << order;
407                 retried = true;
408         }
409
410         if (!vstart)
411                 return -ENOMEM;
412
413         if (remap)
414                 rc = remap(vstart, nslabs);
415         if (rc) {
416                 free_pages((unsigned long)vstart, order);
417
418                 nslabs = ALIGN(nslabs >> 1, IO_TLB_SEGSIZE);
419                 if (nslabs < IO_TLB_MIN_SLABS)
420                         return rc;
421                 retried = true;
422                 goto retry;
423         }
424
425         if (retried) {
426                 pr_warn("only able to allocate %ld MB\n",
427                         (PAGE_SIZE << order) >> 20);
428         }
429
430         if (!default_nareas)
431                 swiotlb_adjust_nareas(num_possible_cpus());
432
433         area_order = get_order(array_size(sizeof(*mem->areas),
434                 default_nareas));
435         mem->areas = (struct io_tlb_area *)
436                 __get_free_pages(GFP_KERNEL | __GFP_ZERO, area_order);
437         if (!mem->areas)
438                 goto error_area;
439
440         mem->slots = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
441                 get_order(array_size(sizeof(*mem->slots), nslabs)));
442         if (!mem->slots)
443                 goto error_slots;
444
445         set_memory_decrypted((unsigned long)vstart,
446                              (nslabs << IO_TLB_SHIFT) >> PAGE_SHIFT);
447         swiotlb_init_io_tlb_mem(mem, virt_to_phys(vstart), nslabs, 0, true,
448                                 default_nareas);
449
450         swiotlb_print_info();
451         return 0;
452
453 error_slots:
454         free_pages((unsigned long)mem->areas, area_order);
455 error_area:
456         free_pages((unsigned long)vstart, order);
457         return -ENOMEM;
458 }
459
460 void __init swiotlb_exit(void)
461 {
462         struct io_tlb_mem *mem = &io_tlb_default_mem;
463         unsigned long tbl_vaddr;
464         size_t tbl_size, slots_size;
465         unsigned int area_order;
466
467         if (swiotlb_force_bounce)
468                 return;
469
470         if (!mem->nslabs)
471                 return;
472
473         pr_info("tearing down default memory pool\n");
474         tbl_vaddr = (unsigned long)phys_to_virt(mem->start);
475         tbl_size = PAGE_ALIGN(mem->end - mem->start);
476         slots_size = PAGE_ALIGN(array_size(sizeof(*mem->slots), mem->nslabs));
477
478         set_memory_encrypted(tbl_vaddr, tbl_size >> PAGE_SHIFT);
479         if (mem->late_alloc) {
480                 area_order = get_order(array_size(sizeof(*mem->areas),
481                         mem->nareas));
482                 free_pages((unsigned long)mem->areas, area_order);
483                 free_pages(tbl_vaddr, get_order(tbl_size));
484                 free_pages((unsigned long)mem->slots, get_order(slots_size));
485         } else {
486                 memblock_free_late(__pa(mem->areas),
487                                    mem->nareas * sizeof(struct io_tlb_area));
488                 memblock_free_late(mem->start, tbl_size);
489                 memblock_free_late(__pa(mem->slots), slots_size);
490         }
491
492         memset(mem, 0, sizeof(*mem));
493 }
494
495 /*
496  * Return the offset into a iotlb slot required to keep the device happy.
497  */
498 static unsigned int swiotlb_align_offset(struct device *dev, u64 addr)
499 {
500         return addr & dma_get_min_align_mask(dev) & (IO_TLB_SIZE - 1);
501 }
502
503 /*
504  * Bounce: copy the swiotlb buffer from or back to the original dma location
505  */
506 static void swiotlb_bounce(struct device *dev, phys_addr_t tlb_addr, size_t size,
507                            enum dma_data_direction dir)
508 {
509         struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
510         int index = (tlb_addr - mem->start) >> IO_TLB_SHIFT;
511         phys_addr_t orig_addr = mem->slots[index].orig_addr;
512         size_t alloc_size = mem->slots[index].alloc_size;
513         unsigned long pfn = PFN_DOWN(orig_addr);
514         unsigned char *vaddr = mem->vaddr + tlb_addr - mem->start;
515         unsigned int tlb_offset, orig_addr_offset;
516
517         if (orig_addr == INVALID_PHYS_ADDR)
518                 return;
519
520         tlb_offset = tlb_addr & (IO_TLB_SIZE - 1);
521         orig_addr_offset = swiotlb_align_offset(dev, orig_addr);
522         if (tlb_offset < orig_addr_offset) {
523                 dev_WARN_ONCE(dev, 1,
524                         "Access before mapping start detected. orig offset %u, requested offset %u.\n",
525                         orig_addr_offset, tlb_offset);
526                 return;
527         }
528
529         tlb_offset -= orig_addr_offset;
530         if (tlb_offset > alloc_size) {
531                 dev_WARN_ONCE(dev, 1,
532                         "Buffer overflow detected. Allocation size: %zu. Mapping size: %zu+%u.\n",
533                         alloc_size, size, tlb_offset);
534                 return;
535         }
536
537         orig_addr += tlb_offset;
538         alloc_size -= tlb_offset;
539
540         if (size > alloc_size) {
541                 dev_WARN_ONCE(dev, 1,
542                         "Buffer overflow detected. Allocation size: %zu. Mapping size: %zu.\n",
543                         alloc_size, size);
544                 size = alloc_size;
545         }
546
547         if (PageHighMem(pfn_to_page(pfn))) {
548                 /* The buffer does not have a mapping.  Map it in and copy */
549                 unsigned int offset = orig_addr & ~PAGE_MASK;
550                 char *buffer;
551                 unsigned int sz = 0;
552                 unsigned long flags;
553
554                 while (size) {
555                         sz = min_t(size_t, PAGE_SIZE - offset, size);
556
557                         local_irq_save(flags);
558                         buffer = kmap_atomic(pfn_to_page(pfn));
559                         if (dir == DMA_TO_DEVICE)
560                                 memcpy(vaddr, buffer + offset, sz);
561                         else
562                                 memcpy(buffer + offset, vaddr, sz);
563                         kunmap_atomic(buffer);
564                         local_irq_restore(flags);
565
566                         size -= sz;
567                         pfn++;
568                         vaddr += sz;
569                         offset = 0;
570                 }
571         } else if (dir == DMA_TO_DEVICE) {
572                 memcpy(vaddr, phys_to_virt(orig_addr), size);
573         } else {
574                 memcpy(phys_to_virt(orig_addr), vaddr, size);
575         }
576 }
577
578 #define slot_addr(start, idx)   ((start) + ((idx) << IO_TLB_SHIFT))
579
580 /*
581  * Carefully handle integer overflow which can occur when boundary_mask == ~0UL.
582  */
583 static inline unsigned long get_max_slots(unsigned long boundary_mask)
584 {
585         if (boundary_mask == ~0UL)
586                 return 1UL << (BITS_PER_LONG - IO_TLB_SHIFT);
587         return nr_slots(boundary_mask + 1);
588 }
589
590 static unsigned int wrap_area_index(struct io_tlb_mem *mem, unsigned int index)
591 {
592         if (index >= mem->area_nslabs)
593                 return 0;
594         return index;
595 }
596
597 /*
598  * Find a suitable number of IO TLB entries size that will fit this request and
599  * allocate a buffer from that IO TLB pool.
600  */
601 static int swiotlb_do_find_slots(struct io_tlb_mem *mem,
602                 struct io_tlb_area *area, int area_index,
603                 struct device *dev, phys_addr_t orig_addr,
604                 size_t alloc_size, unsigned int alloc_align_mask)
605 {
606         unsigned long boundary_mask = dma_get_seg_boundary(dev);
607         dma_addr_t tbl_dma_addr =
608                 phys_to_dma_unencrypted(dev, mem->start) & boundary_mask;
609         unsigned long max_slots = get_max_slots(boundary_mask);
610         unsigned int iotlb_align_mask =
611                 dma_get_min_align_mask(dev) & ~(IO_TLB_SIZE - 1);
612         unsigned int nslots = nr_slots(alloc_size), stride;
613         unsigned int index, wrap, count = 0, i;
614         unsigned int offset = swiotlb_align_offset(dev, orig_addr);
615         unsigned long flags;
616         unsigned int slot_base;
617         unsigned int slot_index;
618
619         BUG_ON(!nslots);
620         BUG_ON(area_index >= mem->nareas);
621
622         /*
623          * For mappings with an alignment requirement don't bother looping to
624          * unaligned slots once we found an aligned one.  For allocations of
625          * PAGE_SIZE or larger only look for page aligned allocations.
626          */
627         stride = (iotlb_align_mask >> IO_TLB_SHIFT) + 1;
628         if (alloc_size >= PAGE_SIZE)
629                 stride = max(stride, stride << (PAGE_SHIFT - IO_TLB_SHIFT));
630         stride = max(stride, (alloc_align_mask >> IO_TLB_SHIFT) + 1);
631
632         spin_lock_irqsave(&area->lock, flags);
633         if (unlikely(nslots > mem->area_nslabs - area->used))
634                 goto not_found;
635
636         slot_base = area_index * mem->area_nslabs;
637         index = wrap = wrap_area_index(mem, ALIGN(area->index, stride));
638
639         do {
640                 slot_index = slot_base + index;
641
642                 if (orig_addr &&
643                     (slot_addr(tbl_dma_addr, slot_index) &
644                      iotlb_align_mask) != (orig_addr & iotlb_align_mask)) {
645                         index = wrap_area_index(mem, index + 1);
646                         continue;
647                 }
648
649                 /*
650                  * If we find a slot that indicates we have 'nslots' number of
651                  * contiguous buffers, we allocate the buffers from that slot
652                  * and mark the entries as '0' indicating unavailable.
653                  */
654                 if (!iommu_is_span_boundary(slot_index, nslots,
655                                             nr_slots(tbl_dma_addr),
656                                             max_slots)) {
657                         if (mem->slots[slot_index].list >= nslots)
658                                 goto found;
659                 }
660                 index = wrap_area_index(mem, index + stride);
661         } while (index != wrap);
662
663 not_found:
664         spin_unlock_irqrestore(&area->lock, flags);
665         return -1;
666
667 found:
668         for (i = slot_index; i < slot_index + nslots; i++) {
669                 mem->slots[i].list = 0;
670                 mem->slots[i].alloc_size = alloc_size - (offset +
671                                 ((i - slot_index) << IO_TLB_SHIFT));
672         }
673         for (i = slot_index - 1;
674              io_tlb_offset(i) != IO_TLB_SEGSIZE - 1 &&
675              mem->slots[i].list; i--)
676                 mem->slots[i].list = ++count;
677
678         /*
679          * Update the indices to avoid searching in the next round.
680          */
681         if (index + nslots < mem->area_nslabs)
682                 area->index = index + nslots;
683         else
684                 area->index = 0;
685         area->used += nslots;
686         spin_unlock_irqrestore(&area->lock, flags);
687         return slot_index;
688 }
689
690 static int swiotlb_find_slots(struct device *dev, phys_addr_t orig_addr,
691                 size_t alloc_size, unsigned int alloc_align_mask)
692 {
693         struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
694         int start = raw_smp_processor_id() & ((1U << __fls(mem->nareas)) - 1);
695         int i = start, index;
696
697         do {
698                 index = swiotlb_do_find_slots(mem, mem->areas + i, i,
699                                               dev, orig_addr, alloc_size,
700                                               alloc_align_mask);
701                 if (index >= 0)
702                         return index;
703                 if (++i >= mem->nareas)
704                         i = 0;
705         } while (i != start);
706
707         return -1;
708 }
709
710 static unsigned long mem_used(struct io_tlb_mem *mem)
711 {
712         int i;
713         unsigned long used = 0;
714
715         for (i = 0; i < mem->nareas; i++)
716                 used += mem->areas[i].used;
717         return used;
718 }
719
720 phys_addr_t swiotlb_tbl_map_single(struct device *dev, phys_addr_t orig_addr,
721                 size_t mapping_size, size_t alloc_size,
722                 unsigned int alloc_align_mask, enum dma_data_direction dir,
723                 unsigned long attrs)
724 {
725         struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
726         unsigned int offset = swiotlb_align_offset(dev, orig_addr);
727         unsigned int i;
728         int index;
729         phys_addr_t tlb_addr;
730
731         if (!mem || !mem->nslabs)
732                 panic("Can not allocate SWIOTLB buffer earlier and can't now provide you with the DMA bounce buffer");
733
734         if (cc_platform_has(CC_ATTR_MEM_ENCRYPT))
735                 pr_warn_once("Memory encryption is active and system is using DMA bounce buffers\n");
736
737         if (mapping_size > alloc_size) {
738                 dev_warn_once(dev, "Invalid sizes (mapping: %zd bytes, alloc: %zd bytes)",
739                               mapping_size, alloc_size);
740                 return (phys_addr_t)DMA_MAPPING_ERROR;
741         }
742
743         index = swiotlb_find_slots(dev, orig_addr,
744                                    alloc_size + offset, alloc_align_mask);
745         if (index == -1) {
746                 if (!(attrs & DMA_ATTR_NO_WARN))
747                         dev_warn_ratelimited(dev,
748         "swiotlb buffer is full (sz: %zd bytes), total %lu (slots), used %lu (slots)\n",
749                                  alloc_size, mem->nslabs, mem_used(mem));
750                 return (phys_addr_t)DMA_MAPPING_ERROR;
751         }
752
753         /*
754          * Save away the mapping from the original address to the DMA address.
755          * This is needed when we sync the memory.  Then we sync the buffer if
756          * needed.
757          */
758         for (i = 0; i < nr_slots(alloc_size + offset); i++)
759                 mem->slots[index + i].orig_addr = slot_addr(orig_addr, i);
760         tlb_addr = slot_addr(mem->start, index) + offset;
761         /*
762          * When dir == DMA_FROM_DEVICE we could omit the copy from the orig
763          * to the tlb buffer, if we knew for sure the device will
764          * overwirte the entire current content. But we don't. Thus
765          * unconditional bounce may prevent leaking swiotlb content (i.e.
766          * kernel memory) to user-space.
767          */
768         swiotlb_bounce(dev, tlb_addr, mapping_size, DMA_TO_DEVICE);
769         return tlb_addr;
770 }
771
772 static void swiotlb_release_slots(struct device *dev, phys_addr_t tlb_addr)
773 {
774         struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
775         unsigned long flags;
776         unsigned int offset = swiotlb_align_offset(dev, tlb_addr);
777         int index = (tlb_addr - offset - mem->start) >> IO_TLB_SHIFT;
778         int nslots = nr_slots(mem->slots[index].alloc_size + offset);
779         int aindex = index / mem->area_nslabs;
780         struct io_tlb_area *area = &mem->areas[aindex];
781         int count, i;
782
783         /*
784          * Return the buffer to the free list by setting the corresponding
785          * entries to indicate the number of contiguous entries available.
786          * While returning the entries to the free list, we merge the entries
787          * with slots below and above the pool being returned.
788          */
789         BUG_ON(aindex >= mem->nareas);
790
791         spin_lock_irqsave(&area->lock, flags);
792         if (index + nslots < ALIGN(index + 1, IO_TLB_SEGSIZE))
793                 count = mem->slots[index + nslots].list;
794         else
795                 count = 0;
796
797         /*
798          * Step 1: return the slots to the free list, merging the slots with
799          * superceeding slots
800          */
801         for (i = index + nslots - 1; i >= index; i--) {
802                 mem->slots[i].list = ++count;
803                 mem->slots[i].orig_addr = INVALID_PHYS_ADDR;
804                 mem->slots[i].alloc_size = 0;
805         }
806
807         /*
808          * Step 2: merge the returned slots with the preceding slots, if
809          * available (non zero)
810          */
811         for (i = index - 1;
812              io_tlb_offset(i) != IO_TLB_SEGSIZE - 1 && mem->slots[i].list;
813              i--)
814                 mem->slots[i].list = ++count;
815         area->used -= nslots;
816         spin_unlock_irqrestore(&area->lock, flags);
817 }
818
819 /*
820  * tlb_addr is the physical address of the bounce buffer to unmap.
821  */
822 void swiotlb_tbl_unmap_single(struct device *dev, phys_addr_t tlb_addr,
823                               size_t mapping_size, enum dma_data_direction dir,
824                               unsigned long attrs)
825 {
826         /*
827          * First, sync the memory before unmapping the entry
828          */
829         if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
830             (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL))
831                 swiotlb_bounce(dev, tlb_addr, mapping_size, DMA_FROM_DEVICE);
832
833         swiotlb_release_slots(dev, tlb_addr);
834 }
835
836 void swiotlb_sync_single_for_device(struct device *dev, phys_addr_t tlb_addr,
837                 size_t size, enum dma_data_direction dir)
838 {
839         if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL)
840                 swiotlb_bounce(dev, tlb_addr, size, DMA_TO_DEVICE);
841         else
842                 BUG_ON(dir != DMA_FROM_DEVICE);
843 }
844
845 void swiotlb_sync_single_for_cpu(struct device *dev, phys_addr_t tlb_addr,
846                 size_t size, enum dma_data_direction dir)
847 {
848         if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
849                 swiotlb_bounce(dev, tlb_addr, size, DMA_FROM_DEVICE);
850         else
851                 BUG_ON(dir != DMA_TO_DEVICE);
852 }
853
854 /*
855  * Create a swiotlb mapping for the buffer at @paddr, and in case of DMAing
856  * to the device copy the data into it as well.
857  */
858 dma_addr_t swiotlb_map(struct device *dev, phys_addr_t paddr, size_t size,
859                 enum dma_data_direction dir, unsigned long attrs)
860 {
861         phys_addr_t swiotlb_addr;
862         dma_addr_t dma_addr;
863
864         trace_swiotlb_bounced(dev, phys_to_dma(dev, paddr), size);
865
866         swiotlb_addr = swiotlb_tbl_map_single(dev, paddr, size, size, 0, dir,
867                         attrs);
868         if (swiotlb_addr == (phys_addr_t)DMA_MAPPING_ERROR)
869                 return DMA_MAPPING_ERROR;
870
871         /* Ensure that the address returned is DMA'ble */
872         dma_addr = phys_to_dma_unencrypted(dev, swiotlb_addr);
873         if (unlikely(!dma_capable(dev, dma_addr, size, true))) {
874                 swiotlb_tbl_unmap_single(dev, swiotlb_addr, size, dir,
875                         attrs | DMA_ATTR_SKIP_CPU_SYNC);
876                 dev_WARN_ONCE(dev, 1,
877                         "swiotlb addr %pad+%zu overflow (mask %llx, bus limit %llx).\n",
878                         &dma_addr, size, *dev->dma_mask, dev->bus_dma_limit);
879                 return DMA_MAPPING_ERROR;
880         }
881
882         if (!dev_is_dma_coherent(dev) && !(attrs & DMA_ATTR_SKIP_CPU_SYNC))
883                 arch_sync_dma_for_device(swiotlb_addr, size, dir);
884         return dma_addr;
885 }
886
887 size_t swiotlb_max_mapping_size(struct device *dev)
888 {
889         int min_align_mask = dma_get_min_align_mask(dev);
890         int min_align = 0;
891
892         /*
893          * swiotlb_find_slots() skips slots according to
894          * min align mask. This affects max mapping size.
895          * Take it into acount here.
896          */
897         if (min_align_mask)
898                 min_align = roundup(min_align_mask, IO_TLB_SIZE);
899
900         return ((size_t)IO_TLB_SIZE) * IO_TLB_SEGSIZE - min_align;
901 }
902
903 bool is_swiotlb_active(struct device *dev)
904 {
905         struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
906
907         return mem && mem->nslabs;
908 }
909 EXPORT_SYMBOL_GPL(is_swiotlb_active);
910
911 static void swiotlb_create_debugfs_files(struct io_tlb_mem *mem,
912                                          const char *dirname)
913 {
914         unsigned long used = mem_used(mem);
915
916         mem->debugfs = debugfs_create_dir(dirname, io_tlb_default_mem.debugfs);
917         if (!mem->nslabs)
918                 return;
919
920         debugfs_create_ulong("io_tlb_nslabs", 0400, mem->debugfs, &mem->nslabs);
921         debugfs_create_ulong("io_tlb_used", 0400, mem->debugfs, &used);
922 }
923
924 static int __init __maybe_unused swiotlb_create_default_debugfs(void)
925 {
926         swiotlb_create_debugfs_files(&io_tlb_default_mem, "swiotlb");
927         return 0;
928 }
929
930 #ifdef CONFIG_DEBUG_FS
931 late_initcall(swiotlb_create_default_debugfs);
932 #endif
933
934 #ifdef CONFIG_DMA_RESTRICTED_POOL
935
936 struct page *swiotlb_alloc(struct device *dev, size_t size)
937 {
938         struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
939         phys_addr_t tlb_addr;
940         int index;
941
942         if (!mem)
943                 return NULL;
944
945         index = swiotlb_find_slots(dev, 0, size, 0);
946         if (index == -1)
947                 return NULL;
948
949         tlb_addr = slot_addr(mem->start, index);
950
951         return pfn_to_page(PFN_DOWN(tlb_addr));
952 }
953
954 bool swiotlb_free(struct device *dev, struct page *page, size_t size)
955 {
956         phys_addr_t tlb_addr = page_to_phys(page);
957
958         if (!is_swiotlb_buffer(dev, tlb_addr))
959                 return false;
960
961         swiotlb_release_slots(dev, tlb_addr);
962
963         return true;
964 }
965
966 static int rmem_swiotlb_device_init(struct reserved_mem *rmem,
967                                     struct device *dev)
968 {
969         struct io_tlb_mem *mem = rmem->priv;
970         unsigned long nslabs = rmem->size >> IO_TLB_SHIFT;
971
972         /* Set Per-device io tlb area to one */
973         unsigned int nareas = 1;
974
975         /*
976          * Since multiple devices can share the same pool, the private data,
977          * io_tlb_mem struct, will be initialized by the first device attached
978          * to it.
979          */
980         if (!mem) {
981                 mem = kzalloc(sizeof(*mem), GFP_KERNEL);
982                 if (!mem)
983                         return -ENOMEM;
984
985                 mem->slots = kcalloc(nslabs, sizeof(*mem->slots), GFP_KERNEL);
986                 if (!mem->slots) {
987                         kfree(mem);
988                         return -ENOMEM;
989                 }
990
991                 mem->areas = kcalloc(nareas, sizeof(*mem->areas),
992                                 GFP_KERNEL);
993                 if (!mem->areas) {
994                         kfree(mem->slots);
995                         kfree(mem);
996                         return -ENOMEM;
997                 }
998
999                 set_memory_decrypted((unsigned long)phys_to_virt(rmem->base),
1000                                      rmem->size >> PAGE_SHIFT);
1001                 swiotlb_init_io_tlb_mem(mem, rmem->base, nslabs, SWIOTLB_FORCE,
1002                                         false, nareas);
1003                 mem->for_alloc = true;
1004
1005                 rmem->priv = mem;
1006
1007                 swiotlb_create_debugfs_files(mem, rmem->name);
1008         }
1009
1010         dev->dma_io_tlb_mem = mem;
1011
1012         return 0;
1013 }
1014
1015 static void rmem_swiotlb_device_release(struct reserved_mem *rmem,
1016                                         struct device *dev)
1017 {
1018         dev->dma_io_tlb_mem = &io_tlb_default_mem;
1019 }
1020
1021 static const struct reserved_mem_ops rmem_swiotlb_ops = {
1022         .device_init = rmem_swiotlb_device_init,
1023         .device_release = rmem_swiotlb_device_release,
1024 };
1025
1026 static int __init rmem_swiotlb_setup(struct reserved_mem *rmem)
1027 {
1028         unsigned long node = rmem->fdt_node;
1029
1030         if (of_get_flat_dt_prop(node, "reusable", NULL) ||
1031             of_get_flat_dt_prop(node, "linux,cma-default", NULL) ||
1032             of_get_flat_dt_prop(node, "linux,dma-default", NULL) ||
1033             of_get_flat_dt_prop(node, "no-map", NULL))
1034                 return -EINVAL;
1035
1036         if (PageHighMem(pfn_to_page(PHYS_PFN(rmem->base)))) {
1037                 pr_err("Restricted DMA pool must be accessible within the linear mapping.");
1038                 return -EINVAL;
1039         }
1040
1041         rmem->ops = &rmem_swiotlb_ops;
1042         pr_info("Reserved memory: created restricted DMA pool at %pa, size %ld MiB\n",
1043                 &rmem->base, (unsigned long)rmem->size / SZ_1M);
1044         return 0;
1045 }
1046
1047 RESERVEDMEM_OF_DECLARE(dma, "restricted-dma-pool", rmem_swiotlb_setup);
1048 #endif /* CONFIG_DMA_RESTRICTED_POOL */