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