GNU Linux-libre 4.19.245-gnu1
[releases.git] / kernel / dma / swiotlb.c
1 /*
2  * Dynamic DMA mapping support.
3  *
4  * This implementation is a fallback for platforms that do not support
5  * I/O TLBs (aka DMA address translation hardware).
6  * Copyright (C) 2000 Asit Mallick <Asit.K.Mallick@intel.com>
7  * Copyright (C) 2000 Goutham Rao <goutham.rao@intel.com>
8  * Copyright (C) 2000, 2003 Hewlett-Packard Co
9  *      David Mosberger-Tang <davidm@hpl.hp.com>
10  *
11  * 03/05/07 davidm      Switch from PCI-DMA to generic device DMA API.
12  * 00/12/13 davidm      Rename to swiotlb.c and add mark_clean() to avoid
13  *                      unnecessary i-cache flushing.
14  * 04/07/.. ak          Better overflow handling. Assorted fixes.
15  * 05/09/10 linville    Add support for syncing ranges, support syncing for
16  *                      DMA_BIDIRECTIONAL mappings, miscellaneous cleanup.
17  * 08/12/11 beckyb      Add highmem support
18  */
19
20 #define pr_fmt(fmt) "software IO TLB: " fmt
21
22 #include <linux/cache.h>
23 #include <linux/dma-direct.h>
24 #include <linux/mm.h>
25 #include <linux/export.h>
26 #include <linux/spinlock.h>
27 #include <linux/string.h>
28 #include <linux/swiotlb.h>
29 #include <linux/pfn.h>
30 #include <linux/types.h>
31 #include <linux/ctype.h>
32 #include <linux/highmem.h>
33 #include <linux/gfp.h>
34 #include <linux/scatterlist.h>
35 #include <linux/mem_encrypt.h>
36 #include <linux/set_memory.h>
37
38 #include <asm/io.h>
39 #include <asm/dma.h>
40
41 #include <linux/init.h>
42 #include <linux/bootmem.h>
43 #include <linux/iommu-helper.h>
44
45 #define CREATE_TRACE_POINTS
46 #include <trace/events/swiotlb.h>
47
48 #define OFFSET(val,align) ((unsigned long)      \
49                            ( (val) & ( (align) - 1)))
50
51 #define SLABS_PER_PAGE (1 << (PAGE_SHIFT - IO_TLB_SHIFT))
52
53 /*
54  * Minimum IO TLB size to bother booting with.  Systems with mainly
55  * 64bit capable cards will only lightly use the swiotlb.  If we can't
56  * allocate a contiguous 1MB, we're probably in trouble anyway.
57  */
58 #define IO_TLB_MIN_SLABS ((1<<20) >> IO_TLB_SHIFT)
59
60 enum swiotlb_force swiotlb_force;
61
62 /*
63  * Used to do a quick range check in swiotlb_tbl_unmap_single and
64  * swiotlb_tbl_sync_single_*, to see if the memory was in fact allocated by this
65  * API.
66  */
67 static phys_addr_t io_tlb_start, io_tlb_end;
68
69 /*
70  * The number of IO TLB blocks (in groups of 64) between io_tlb_start and
71  * io_tlb_end.  This is command line adjustable via setup_io_tlb_npages.
72  */
73 static unsigned long io_tlb_nslabs;
74
75 /*
76  * When the IOMMU overflows we return a fallback buffer. This sets the size.
77  */
78 static unsigned long io_tlb_overflow = 32*1024;
79
80 static phys_addr_t io_tlb_overflow_buffer;
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 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 /* make io_tlb_overflow tunable too? */
130
131 unsigned long swiotlb_nr_tbl(void)
132 {
133         return io_tlb_nslabs;
134 }
135 EXPORT_SYMBOL_GPL(swiotlb_nr_tbl);
136
137 unsigned int swiotlb_max_segment(void)
138 {
139         return max_segment;
140 }
141 EXPORT_SYMBOL_GPL(swiotlb_max_segment);
142
143 void swiotlb_set_max_segment(unsigned int val)
144 {
145         if (swiotlb_force == SWIOTLB_FORCE)
146                 max_segment = 1;
147         else
148                 max_segment = rounddown(val, PAGE_SIZE);
149 }
150
151 /* default to 64MB */
152 #define IO_TLB_DEFAULT_SIZE (64UL<<20)
153 unsigned long swiotlb_size_or_default(void)
154 {
155         unsigned long size;
156
157         size = io_tlb_nslabs << IO_TLB_SHIFT;
158
159         return size ? size : (IO_TLB_DEFAULT_SIZE);
160 }
161
162 static bool no_iotlb_memory;
163
164 void swiotlb_print_info(void)
165 {
166         unsigned long bytes = io_tlb_nslabs << IO_TLB_SHIFT;
167
168         if (no_iotlb_memory) {
169                 pr_warn("No low mem\n");
170                 return;
171         }
172
173         pr_info("mapped [mem %#010llx-%#010llx] (%luMB)\n",
174                (unsigned long long)io_tlb_start,
175                (unsigned long long)io_tlb_end,
176                bytes >> 20);
177 }
178
179 /*
180  * Early SWIOTLB allocation may be too early to allow an architecture to
181  * perform the desired operations.  This function allows the architecture to
182  * call SWIOTLB when the operations are possible.  It needs to be called
183  * before the SWIOTLB memory is used.
184  */
185 void __init swiotlb_update_mem_attributes(void)
186 {
187         void *vaddr;
188         unsigned long bytes;
189
190         if (no_iotlb_memory || late_alloc)
191                 return;
192
193         vaddr = phys_to_virt(io_tlb_start);
194         bytes = PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT);
195         set_memory_decrypted((unsigned long)vaddr, bytes >> PAGE_SHIFT);
196         memset(vaddr, 0, bytes);
197
198         vaddr = phys_to_virt(io_tlb_overflow_buffer);
199         bytes = PAGE_ALIGN(io_tlb_overflow);
200         set_memory_decrypted((unsigned long)vaddr, bytes >> PAGE_SHIFT);
201         memset(vaddr, 0, bytes);
202 }
203
204 int __init swiotlb_init_with_tbl(char *tlb, unsigned long nslabs, int verbose)
205 {
206         void *v_overflow_buffer;
207         unsigned long i, bytes;
208
209         bytes = nslabs << IO_TLB_SHIFT;
210
211         io_tlb_nslabs = nslabs;
212         io_tlb_start = __pa(tlb);
213         io_tlb_end = io_tlb_start + bytes;
214
215         /*
216          * Get the overflow emergency buffer
217          */
218         v_overflow_buffer = memblock_virt_alloc_low_nopanic(
219                                                 PAGE_ALIGN(io_tlb_overflow),
220                                                 PAGE_SIZE);
221         if (!v_overflow_buffer)
222                 return -ENOMEM;
223
224         io_tlb_overflow_buffer = __pa(v_overflow_buffer);
225
226         /*
227          * Allocate and initialize the free list array.  This array is used
228          * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
229          * between io_tlb_start and io_tlb_end.
230          */
231         io_tlb_list = memblock_virt_alloc(
232                                 PAGE_ALIGN(io_tlb_nslabs * sizeof(int)),
233                                 PAGE_SIZE);
234         io_tlb_orig_addr = memblock_virt_alloc(
235                                 PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)),
236                                 PAGE_SIZE);
237         for (i = 0; i < io_tlb_nslabs; i++) {
238                 io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE);
239                 io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
240         }
241         io_tlb_index = 0;
242         no_iotlb_memory = false;
243
244         if (verbose)
245                 swiotlb_print_info();
246
247         swiotlb_set_max_segment(io_tlb_nslabs << IO_TLB_SHIFT);
248         return 0;
249 }
250
251 /*
252  * Statically reserve bounce buffer space and initialize bounce buffer data
253  * structures for the software IO TLB used to implement the DMA API.
254  */
255 void  __init
256 swiotlb_init(int verbose)
257 {
258         size_t default_size = IO_TLB_DEFAULT_SIZE;
259         unsigned char *vstart;
260         unsigned long bytes;
261
262         if (!io_tlb_nslabs) {
263                 io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
264                 io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
265         }
266
267         bytes = io_tlb_nslabs << IO_TLB_SHIFT;
268
269         /* Get IO TLB memory from the low pages */
270         vstart = memblock_virt_alloc_low_nopanic(PAGE_ALIGN(bytes), PAGE_SIZE);
271         if (vstart && !swiotlb_init_with_tbl(vstart, io_tlb_nslabs, verbose))
272                 return;
273
274         if (io_tlb_start) {
275                 memblock_free_early(io_tlb_start,
276                                     PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
277                 io_tlb_start = 0;
278         }
279         pr_warn("Cannot allocate buffer");
280         no_iotlb_memory = true;
281 }
282
283 /*
284  * Systems with larger DMA zones (those that don't support ISA) can
285  * initialize the swiotlb later using the slab allocator if needed.
286  * This should be just like above, but with some error catching.
287  */
288 int
289 swiotlb_late_init_with_default_size(size_t default_size)
290 {
291         unsigned long bytes, req_nslabs = io_tlb_nslabs;
292         unsigned char *vstart = NULL;
293         unsigned int order;
294         int rc = 0;
295
296         if (!io_tlb_nslabs) {
297                 io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
298                 io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
299         }
300
301         /*
302          * Get IO TLB memory from the low pages
303          */
304         order = get_order(io_tlb_nslabs << IO_TLB_SHIFT);
305         io_tlb_nslabs = SLABS_PER_PAGE << order;
306         bytes = io_tlb_nslabs << IO_TLB_SHIFT;
307
308         while ((SLABS_PER_PAGE << order) > IO_TLB_MIN_SLABS) {
309                 vstart = (void *)__get_free_pages(GFP_DMA | __GFP_NOWARN,
310                                                   order);
311                 if (vstart)
312                         break;
313                 order--;
314         }
315
316         if (!vstart) {
317                 io_tlb_nslabs = req_nslabs;
318                 return -ENOMEM;
319         }
320         if (order != get_order(bytes)) {
321                 pr_warn("only able to allocate %ld MB\n",
322                         (PAGE_SIZE << order) >> 20);
323                 io_tlb_nslabs = SLABS_PER_PAGE << order;
324         }
325         rc = swiotlb_late_init_with_tbl(vstart, io_tlb_nslabs);
326         if (rc)
327                 free_pages((unsigned long)vstart, order);
328
329         return rc;
330 }
331
332 int
333 swiotlb_late_init_with_tbl(char *tlb, unsigned long nslabs)
334 {
335         unsigned long i, bytes;
336         unsigned char *v_overflow_buffer;
337
338         bytes = nslabs << IO_TLB_SHIFT;
339
340         io_tlb_nslabs = nslabs;
341         io_tlb_start = virt_to_phys(tlb);
342         io_tlb_end = io_tlb_start + bytes;
343
344         set_memory_decrypted((unsigned long)tlb, bytes >> PAGE_SHIFT);
345         memset(tlb, 0, bytes);
346
347         /*
348          * Get the overflow emergency buffer
349          */
350         v_overflow_buffer = (void *)__get_free_pages(GFP_DMA,
351                                                      get_order(io_tlb_overflow));
352         if (!v_overflow_buffer)
353                 goto cleanup2;
354
355         set_memory_decrypted((unsigned long)v_overflow_buffer,
356                         io_tlb_overflow >> PAGE_SHIFT);
357         memset(v_overflow_buffer, 0, io_tlb_overflow);
358         io_tlb_overflow_buffer = virt_to_phys(v_overflow_buffer);
359
360         /*
361          * Allocate and initialize the free list array.  This array is used
362          * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
363          * between io_tlb_start and io_tlb_end.
364          */
365         io_tlb_list = (unsigned int *)__get_free_pages(GFP_KERNEL,
366                                       get_order(io_tlb_nslabs * sizeof(int)));
367         if (!io_tlb_list)
368                 goto cleanup3;
369
370         io_tlb_orig_addr = (phys_addr_t *)
371                 __get_free_pages(GFP_KERNEL,
372                                  get_order(io_tlb_nslabs *
373                                            sizeof(phys_addr_t)));
374         if (!io_tlb_orig_addr)
375                 goto cleanup4;
376
377         for (i = 0; i < io_tlb_nslabs; i++) {
378                 io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE);
379                 io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
380         }
381         io_tlb_index = 0;
382         no_iotlb_memory = false;
383
384         swiotlb_print_info();
385
386         late_alloc = 1;
387
388         swiotlb_set_max_segment(io_tlb_nslabs << IO_TLB_SHIFT);
389
390         return 0;
391
392 cleanup4:
393         free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
394                                                          sizeof(int)));
395         io_tlb_list = NULL;
396 cleanup3:
397         free_pages((unsigned long)v_overflow_buffer,
398                    get_order(io_tlb_overflow));
399         io_tlb_overflow_buffer = 0;
400 cleanup2:
401         io_tlb_end = 0;
402         io_tlb_start = 0;
403         io_tlb_nslabs = 0;
404         max_segment = 0;
405         return -ENOMEM;
406 }
407
408 void __init swiotlb_exit(void)
409 {
410         if (!io_tlb_orig_addr)
411                 return;
412
413         if (late_alloc) {
414                 free_pages((unsigned long)phys_to_virt(io_tlb_overflow_buffer),
415                            get_order(io_tlb_overflow));
416                 free_pages((unsigned long)io_tlb_orig_addr,
417                            get_order(io_tlb_nslabs * sizeof(phys_addr_t)));
418                 free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs *
419                                                                  sizeof(int)));
420                 free_pages((unsigned long)phys_to_virt(io_tlb_start),
421                            get_order(io_tlb_nslabs << IO_TLB_SHIFT));
422         } else {
423                 memblock_free_late(io_tlb_overflow_buffer,
424                                    PAGE_ALIGN(io_tlb_overflow));
425                 memblock_free_late(__pa(io_tlb_orig_addr),
426                                    PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)));
427                 memblock_free_late(__pa(io_tlb_list),
428                                    PAGE_ALIGN(io_tlb_nslabs * sizeof(int)));
429                 memblock_free_late(io_tlb_start,
430                                    PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
431         }
432         io_tlb_nslabs = 0;
433         max_segment = 0;
434 }
435
436 int is_swiotlb_buffer(phys_addr_t paddr)
437 {
438         return paddr >= io_tlb_start && paddr < io_tlb_end;
439 }
440
441 /*
442  * Bounce: copy the swiotlb buffer back to the original dma location
443  */
444 static void swiotlb_bounce(phys_addr_t orig_addr, phys_addr_t tlb_addr,
445                            size_t size, enum dma_data_direction dir)
446 {
447         unsigned long pfn = PFN_DOWN(orig_addr);
448         unsigned char *vaddr = phys_to_virt(tlb_addr);
449
450         if (PageHighMem(pfn_to_page(pfn))) {
451                 /* The buffer does not have a mapping.  Map it in and copy */
452                 unsigned int offset = orig_addr & ~PAGE_MASK;
453                 char *buffer;
454                 unsigned int sz = 0;
455                 unsigned long flags;
456
457                 while (size) {
458                         sz = min_t(size_t, PAGE_SIZE - offset, size);
459
460                         local_irq_save(flags);
461                         buffer = kmap_atomic(pfn_to_page(pfn));
462                         if (dir == DMA_TO_DEVICE)
463                                 memcpy(vaddr, buffer + offset, sz);
464                         else
465                                 memcpy(buffer + offset, vaddr, sz);
466                         kunmap_atomic(buffer);
467                         local_irq_restore(flags);
468
469                         size -= sz;
470                         pfn++;
471                         vaddr += sz;
472                         offset = 0;
473                 }
474         } else if (dir == DMA_TO_DEVICE) {
475                 memcpy(vaddr, phys_to_virt(orig_addr), size);
476         } else {
477                 memcpy(phys_to_virt(orig_addr), vaddr, size);
478         }
479 }
480
481 phys_addr_t swiotlb_tbl_map_single(struct device *hwdev,
482                                    dma_addr_t tbl_dma_addr,
483                                    phys_addr_t orig_addr, size_t size,
484                                    enum dma_data_direction dir,
485                                    unsigned long attrs)
486 {
487         unsigned long flags;
488         phys_addr_t tlb_addr;
489         unsigned int nslots, stride, index, wrap;
490         int i;
491         unsigned long mask;
492         unsigned long offset_slots;
493         unsigned long max_slots;
494
495         if (no_iotlb_memory)
496                 panic("Can not allocate SWIOTLB buffer earlier and can't now provide you with the DMA bounce buffer");
497
498         if (mem_encrypt_active())
499                 pr_warn_once("%s is active and system is using DMA bounce buffers\n",
500                              sme_active() ? "SME" : "SEV");
501
502         mask = dma_get_seg_boundary(hwdev);
503
504         tbl_dma_addr &= mask;
505
506         offset_slots = ALIGN(tbl_dma_addr, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
507
508         /*
509          * Carefully handle integer overflow which can occur when mask == ~0UL.
510          */
511         max_slots = mask + 1
512                     ? ALIGN(mask + 1, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT
513                     : 1UL << (BITS_PER_LONG - IO_TLB_SHIFT);
514
515         /*
516          * For mappings greater than or equal to a page, we limit the stride
517          * (and hence alignment) to a page size.
518          */
519         nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
520         if (size >= PAGE_SIZE)
521                 stride = (1 << (PAGE_SHIFT - IO_TLB_SHIFT));
522         else
523                 stride = 1;
524
525         BUG_ON(!nslots);
526
527         /*
528          * Find suitable number of IO TLB entries size that will fit this
529          * request and allocate a buffer from that IO TLB pool.
530          */
531         spin_lock_irqsave(&io_tlb_lock, flags);
532         index = ALIGN(io_tlb_index, stride);
533         if (index >= io_tlb_nslabs)
534                 index = 0;
535         wrap = index;
536
537         do {
538                 while (iommu_is_span_boundary(index, nslots, offset_slots,
539                                               max_slots)) {
540                         index += stride;
541                         if (index >= io_tlb_nslabs)
542                                 index = 0;
543                         if (index == wrap)
544                                 goto not_found;
545                 }
546
547                 /*
548                  * If we find a slot that indicates we have 'nslots' number of
549                  * contiguous buffers, we allocate the buffers from that slot
550                  * and mark the entries as '0' indicating unavailable.
551                  */
552                 if (io_tlb_list[index] >= nslots) {
553                         int count = 0;
554
555                         for (i = index; i < (int) (index + nslots); i++)
556                                 io_tlb_list[i] = 0;
557                         for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE - 1) && io_tlb_list[i]; i--)
558                                 io_tlb_list[i] = ++count;
559                         tlb_addr = io_tlb_start + (index << IO_TLB_SHIFT);
560
561                         /*
562                          * Update the indices to avoid searching in the next
563                          * round.
564                          */
565                         io_tlb_index = ((index + nslots) < io_tlb_nslabs
566                                         ? (index + nslots) : 0);
567
568                         goto found;
569                 }
570                 index += stride;
571                 if (index >= io_tlb_nslabs)
572                         index = 0;
573         } while (index != wrap);
574
575 not_found:
576         spin_unlock_irqrestore(&io_tlb_lock, flags);
577         if (!(attrs & DMA_ATTR_NO_WARN) && printk_ratelimit())
578                 dev_warn(hwdev, "swiotlb buffer is full (sz: %zd bytes)\n", size);
579         return SWIOTLB_MAP_ERROR;
580 found:
581         spin_unlock_irqrestore(&io_tlb_lock, flags);
582
583         /*
584          * Save away the mapping from the original address to the DMA address.
585          * This is needed when we sync the memory.  Then we sync the buffer if
586          * needed.
587          */
588         for (i = 0; i < nslots; i++)
589                 io_tlb_orig_addr[index+i] = orig_addr + (i << IO_TLB_SHIFT);
590         /*
591          * When dir == DMA_FROM_DEVICE we could omit the copy from the orig
592          * to the tlb buffer, if we knew for sure the device will
593          * overwirte the entire current content. But we don't. Thus
594          * unconditional bounce may prevent leaking swiotlb content (i.e.
595          * kernel memory) to user-space.
596          */
597         swiotlb_bounce(orig_addr, tlb_addr, size, DMA_TO_DEVICE);
598         return tlb_addr;
599 }
600
601 /*
602  * Allocates bounce buffer and returns its physical address.
603  */
604 static phys_addr_t
605 map_single(struct device *hwdev, phys_addr_t phys, size_t size,
606            enum dma_data_direction dir, unsigned long attrs)
607 {
608         dma_addr_t start_dma_addr;
609
610         if (swiotlb_force == SWIOTLB_NO_FORCE) {
611                 dev_warn_ratelimited(hwdev, "Cannot do DMA to address %pa\n",
612                                      &phys);
613                 return SWIOTLB_MAP_ERROR;
614         }
615
616         start_dma_addr = __phys_to_dma(hwdev, io_tlb_start);
617         return swiotlb_tbl_map_single(hwdev, start_dma_addr, phys, size,
618                                       dir, attrs);
619 }
620
621 /*
622  * tlb_addr is the physical address of the bounce buffer to unmap.
623  */
624 void swiotlb_tbl_unmap_single(struct device *hwdev, phys_addr_t tlb_addr,
625                               size_t size, enum dma_data_direction dir,
626                               unsigned long attrs)
627 {
628         unsigned long flags;
629         int i, count, nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
630         int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT;
631         phys_addr_t orig_addr = io_tlb_orig_addr[index];
632
633         /*
634          * First, sync the memory before unmapping the entry
635          */
636         if (orig_addr != INVALID_PHYS_ADDR &&
637             !(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
638             ((dir == DMA_FROM_DEVICE) || (dir == DMA_BIDIRECTIONAL)))
639                 swiotlb_bounce(orig_addr, tlb_addr, size, DMA_FROM_DEVICE);
640
641         /*
642          * Return the buffer to the free list by setting the corresponding
643          * entries to indicate the number of contiguous entries available.
644          * While returning the entries to the free list, we merge the entries
645          * with slots below and above the pool being returned.
646          */
647         spin_lock_irqsave(&io_tlb_lock, flags);
648         {
649                 count = ((index + nslots) < ALIGN(index + 1, IO_TLB_SEGSIZE) ?
650                          io_tlb_list[index + nslots] : 0);
651                 /*
652                  * Step 1: return the slots to the free list, merging the
653                  * slots with superceeding slots
654                  */
655                 for (i = index + nslots - 1; i >= index; i--) {
656                         io_tlb_list[i] = ++count;
657                         io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
658                 }
659                 /*
660                  * Step 2: merge the returned slots with the preceding slots,
661                  * if available (non zero)
662                  */
663                 for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE -1) && io_tlb_list[i]; i--)
664                         io_tlb_list[i] = ++count;
665         }
666         spin_unlock_irqrestore(&io_tlb_lock, flags);
667 }
668
669 void swiotlb_tbl_sync_single(struct device *hwdev, phys_addr_t tlb_addr,
670                              size_t size, enum dma_data_direction dir,
671                              enum dma_sync_target target)
672 {
673         int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT;
674         phys_addr_t orig_addr = io_tlb_orig_addr[index];
675
676         if (orig_addr == INVALID_PHYS_ADDR)
677                 return;
678         orig_addr += (unsigned long)tlb_addr & ((1 << IO_TLB_SHIFT) - 1);
679
680         switch (target) {
681         case SYNC_FOR_CPU:
682                 if (likely(dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL))
683                         swiotlb_bounce(orig_addr, tlb_addr,
684                                        size, DMA_FROM_DEVICE);
685                 else
686                         BUG_ON(dir != DMA_TO_DEVICE);
687                 break;
688         case SYNC_FOR_DEVICE:
689                 if (likely(dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL))
690                         swiotlb_bounce(orig_addr, tlb_addr,
691                                        size, DMA_TO_DEVICE);
692                 else
693                         BUG_ON(dir != DMA_FROM_DEVICE);
694                 break;
695         default:
696                 BUG();
697         }
698 }
699
700 static inline bool dma_coherent_ok(struct device *dev, dma_addr_t addr,
701                 size_t size)
702 {
703         u64 mask = DMA_BIT_MASK(32);
704
705         if (dev && dev->coherent_dma_mask)
706                 mask = dev->coherent_dma_mask;
707         return addr + size - 1 <= mask;
708 }
709
710 static void *
711 swiotlb_alloc_buffer(struct device *dev, size_t size, dma_addr_t *dma_handle,
712                 unsigned long attrs)
713 {
714         phys_addr_t phys_addr;
715
716         if (swiotlb_force == SWIOTLB_NO_FORCE)
717                 goto out_warn;
718
719         phys_addr = swiotlb_tbl_map_single(dev,
720                         __phys_to_dma(dev, io_tlb_start),
721                         0, size, DMA_FROM_DEVICE, attrs);
722         if (phys_addr == SWIOTLB_MAP_ERROR)
723                 goto out_warn;
724
725         *dma_handle = __phys_to_dma(dev, phys_addr);
726         if (!dma_coherent_ok(dev, *dma_handle, size))
727                 goto out_unmap;
728
729         memset(phys_to_virt(phys_addr), 0, size);
730         return phys_to_virt(phys_addr);
731
732 out_unmap:
733         dev_warn(dev, "hwdev DMA mask = 0x%016Lx, dev_addr = 0x%016Lx\n",
734                 (unsigned long long)dev->coherent_dma_mask,
735                 (unsigned long long)*dma_handle);
736
737         /*
738          * DMA_TO_DEVICE to avoid memcpy in unmap_single.
739          * DMA_ATTR_SKIP_CPU_SYNC is optional.
740          */
741         swiotlb_tbl_unmap_single(dev, phys_addr, size, DMA_TO_DEVICE,
742                         DMA_ATTR_SKIP_CPU_SYNC);
743 out_warn:
744         if (!(attrs & DMA_ATTR_NO_WARN) && printk_ratelimit()) {
745                 dev_warn(dev,
746                         "swiotlb: coherent allocation failed, size=%zu\n",
747                         size);
748                 dump_stack();
749         }
750         return NULL;
751 }
752
753 static bool swiotlb_free_buffer(struct device *dev, size_t size,
754                 dma_addr_t dma_addr)
755 {
756         phys_addr_t phys_addr = dma_to_phys(dev, dma_addr);
757
758         WARN_ON_ONCE(irqs_disabled());
759
760         if (!is_swiotlb_buffer(phys_addr))
761                 return false;
762
763         /*
764          * DMA_TO_DEVICE to avoid memcpy in swiotlb_tbl_unmap_single.
765          * DMA_ATTR_SKIP_CPU_SYNC is optional.
766          */
767         swiotlb_tbl_unmap_single(dev, phys_addr, size, DMA_TO_DEVICE,
768                                  DMA_ATTR_SKIP_CPU_SYNC);
769         return true;
770 }
771
772 /*
773  * Map a single buffer of the indicated size for DMA in streaming mode.  The
774  * physical address to use is returned.
775  *
776  * Once the device is given the dma address, the device owns this memory until
777  * either swiotlb_unmap_page or swiotlb_dma_sync_single is performed.
778  */
779 dma_addr_t swiotlb_map_page(struct device *dev, struct page *page,
780                             unsigned long offset, size_t size,
781                             enum dma_data_direction dir,
782                             unsigned long attrs)
783 {
784         phys_addr_t map, phys = page_to_phys(page) + offset;
785         dma_addr_t dev_addr = phys_to_dma(dev, phys);
786
787         BUG_ON(dir == DMA_NONE);
788         /*
789          * If the address happens to be in the device's DMA window,
790          * we can safely return the device addr and not worry about bounce
791          * buffering it.
792          */
793         if (dma_capable(dev, dev_addr, size) && swiotlb_force != SWIOTLB_FORCE)
794                 return dev_addr;
795
796         trace_swiotlb_bounced(dev, dev_addr, size, swiotlb_force);
797
798         /* Oh well, have to allocate and map a bounce buffer. */
799         map = map_single(dev, phys, size, dir, attrs);
800         if (map == SWIOTLB_MAP_ERROR)
801                 return __phys_to_dma(dev, io_tlb_overflow_buffer);
802
803         dev_addr = __phys_to_dma(dev, map);
804
805         /* Ensure that the address returned is DMA'ble */
806         if (dma_capable(dev, dev_addr, size))
807                 return dev_addr;
808
809         attrs |= DMA_ATTR_SKIP_CPU_SYNC;
810         swiotlb_tbl_unmap_single(dev, map, size, dir, attrs);
811
812         return __phys_to_dma(dev, io_tlb_overflow_buffer);
813 }
814
815 /*
816  * Unmap a single streaming mode DMA translation.  The dma_addr and size must
817  * match what was provided for in a previous swiotlb_map_page call.  All
818  * other usages are undefined.
819  *
820  * After this call, reads by the cpu to the buffer are guaranteed to see
821  * whatever the device wrote there.
822  */
823 static void unmap_single(struct device *hwdev, dma_addr_t dev_addr,
824                          size_t size, enum dma_data_direction dir,
825                          unsigned long attrs)
826 {
827         phys_addr_t paddr = dma_to_phys(hwdev, dev_addr);
828
829         BUG_ON(dir == DMA_NONE);
830
831         if (is_swiotlb_buffer(paddr)) {
832                 swiotlb_tbl_unmap_single(hwdev, paddr, size, dir, attrs);
833                 return;
834         }
835
836         if (dir != DMA_FROM_DEVICE)
837                 return;
838
839         /*
840          * phys_to_virt doesn't work with hihgmem page but we could
841          * call dma_mark_clean() with hihgmem page here. However, we
842          * are fine since dma_mark_clean() is null on POWERPC. We can
843          * make dma_mark_clean() take a physical address if necessary.
844          */
845         dma_mark_clean(phys_to_virt(paddr), size);
846 }
847
848 void swiotlb_unmap_page(struct device *hwdev, dma_addr_t dev_addr,
849                         size_t size, enum dma_data_direction dir,
850                         unsigned long attrs)
851 {
852         unmap_single(hwdev, dev_addr, size, dir, attrs);
853 }
854
855 /*
856  * Make physical memory consistent for a single streaming mode DMA translation
857  * after a transfer.
858  *
859  * If you perform a swiotlb_map_page() but wish to interrogate the buffer
860  * using the cpu, yet do not wish to teardown the dma mapping, you must
861  * call this function before doing so.  At the next point you give the dma
862  * address back to the card, you must first perform a
863  * swiotlb_dma_sync_for_device, and then the device again owns the buffer
864  */
865 static void
866 swiotlb_sync_single(struct device *hwdev, dma_addr_t dev_addr,
867                     size_t size, enum dma_data_direction dir,
868                     enum dma_sync_target target)
869 {
870         phys_addr_t paddr = dma_to_phys(hwdev, dev_addr);
871
872         BUG_ON(dir == DMA_NONE);
873
874         if (is_swiotlb_buffer(paddr)) {
875                 swiotlb_tbl_sync_single(hwdev, paddr, size, dir, target);
876                 return;
877         }
878
879         if (dir != DMA_FROM_DEVICE)
880                 return;
881
882         dma_mark_clean(phys_to_virt(paddr), size);
883 }
884
885 void
886 swiotlb_sync_single_for_cpu(struct device *hwdev, dma_addr_t dev_addr,
887                             size_t size, enum dma_data_direction dir)
888 {
889         swiotlb_sync_single(hwdev, dev_addr, size, dir, SYNC_FOR_CPU);
890 }
891
892 void
893 swiotlb_sync_single_for_device(struct device *hwdev, dma_addr_t dev_addr,
894                                size_t size, enum dma_data_direction dir)
895 {
896         swiotlb_sync_single(hwdev, dev_addr, size, dir, SYNC_FOR_DEVICE);
897 }
898
899 /*
900  * Map a set of buffers described by scatterlist in streaming mode for DMA.
901  * This is the scatter-gather version of the above swiotlb_map_page
902  * interface.  Here the scatter gather list elements are each tagged with the
903  * appropriate dma address and length.  They are obtained via
904  * sg_dma_{address,length}(SG).
905  *
906  * NOTE: An implementation may be able to use a smaller number of
907  *       DMA address/length pairs than there are SG table elements.
908  *       (for example via virtual mapping capabilities)
909  *       The routine returns the number of addr/length pairs actually
910  *       used, at most nents.
911  *
912  * Device ownership issues as mentioned above for swiotlb_map_page are the
913  * same here.
914  */
915 int
916 swiotlb_map_sg_attrs(struct device *hwdev, struct scatterlist *sgl, int nelems,
917                      enum dma_data_direction dir, unsigned long attrs)
918 {
919         struct scatterlist *sg;
920         int i;
921
922         BUG_ON(dir == DMA_NONE);
923
924         for_each_sg(sgl, sg, nelems, i) {
925                 phys_addr_t paddr = sg_phys(sg);
926                 dma_addr_t dev_addr = phys_to_dma(hwdev, paddr);
927
928                 if (swiotlb_force == SWIOTLB_FORCE ||
929                     !dma_capable(hwdev, dev_addr, sg->length)) {
930                         phys_addr_t map = map_single(hwdev, sg_phys(sg),
931                                                      sg->length, dir, attrs);
932                         if (map == SWIOTLB_MAP_ERROR) {
933                                 /* Don't panic here, we expect map_sg users
934                                    to do proper error handling. */
935                                 attrs |= DMA_ATTR_SKIP_CPU_SYNC;
936                                 swiotlb_unmap_sg_attrs(hwdev, sgl, i, dir,
937                                                        attrs);
938                                 sg_dma_len(sgl) = 0;
939                                 return 0;
940                         }
941                         sg->dma_address = __phys_to_dma(hwdev, map);
942                 } else
943                         sg->dma_address = dev_addr;
944                 sg_dma_len(sg) = sg->length;
945         }
946         return nelems;
947 }
948
949 /*
950  * Unmap a set of streaming mode DMA translations.  Again, cpu read rules
951  * concerning calls here are the same as for swiotlb_unmap_page() above.
952  */
953 void
954 swiotlb_unmap_sg_attrs(struct device *hwdev, struct scatterlist *sgl,
955                        int nelems, enum dma_data_direction dir,
956                        unsigned long attrs)
957 {
958         struct scatterlist *sg;
959         int i;
960
961         BUG_ON(dir == DMA_NONE);
962
963         for_each_sg(sgl, sg, nelems, i)
964                 unmap_single(hwdev, sg->dma_address, sg_dma_len(sg), dir,
965                              attrs);
966 }
967
968 /*
969  * Make physical memory consistent for a set of streaming mode DMA translations
970  * after a transfer.
971  *
972  * The same as swiotlb_sync_single_* but for a scatter-gather list, same rules
973  * and usage.
974  */
975 static void
976 swiotlb_sync_sg(struct device *hwdev, struct scatterlist *sgl,
977                 int nelems, enum dma_data_direction dir,
978                 enum dma_sync_target target)
979 {
980         struct scatterlist *sg;
981         int i;
982
983         for_each_sg(sgl, sg, nelems, i)
984                 swiotlb_sync_single(hwdev, sg->dma_address,
985                                     sg_dma_len(sg), dir, target);
986 }
987
988 void
989 swiotlb_sync_sg_for_cpu(struct device *hwdev, struct scatterlist *sg,
990                         int nelems, enum dma_data_direction dir)
991 {
992         swiotlb_sync_sg(hwdev, sg, nelems, dir, SYNC_FOR_CPU);
993 }
994
995 void
996 swiotlb_sync_sg_for_device(struct device *hwdev, struct scatterlist *sg,
997                            int nelems, enum dma_data_direction dir)
998 {
999         swiotlb_sync_sg(hwdev, sg, nelems, dir, SYNC_FOR_DEVICE);
1000 }
1001
1002 int
1003 swiotlb_dma_mapping_error(struct device *hwdev, dma_addr_t dma_addr)
1004 {
1005         return (dma_addr == __phys_to_dma(hwdev, io_tlb_overflow_buffer));
1006 }
1007
1008 /*
1009  * Return whether the given device DMA address mask can be supported
1010  * properly.  For example, if your device can only drive the low 24-bits
1011  * during bus mastering, then you would pass 0x00ffffff as the mask to
1012  * this function.
1013  */
1014 int
1015 swiotlb_dma_supported(struct device *hwdev, u64 mask)
1016 {
1017         return __phys_to_dma(hwdev, io_tlb_end - 1) <= mask;
1018 }
1019
1020 void *swiotlb_alloc(struct device *dev, size_t size, dma_addr_t *dma_handle,
1021                 gfp_t gfp, unsigned long attrs)
1022 {
1023         void *vaddr;
1024
1025         /* temporary workaround: */
1026         if (gfp & __GFP_NOWARN)
1027                 attrs |= DMA_ATTR_NO_WARN;
1028
1029         /*
1030          * Don't print a warning when the first allocation attempt fails.
1031          * swiotlb_alloc_coherent() will print a warning when the DMA memory
1032          * allocation ultimately failed.
1033          */
1034         gfp |= __GFP_NOWARN;
1035
1036         vaddr = dma_direct_alloc(dev, size, dma_handle, gfp, attrs);
1037         if (!vaddr)
1038                 vaddr = swiotlb_alloc_buffer(dev, size, dma_handle, attrs);
1039         return vaddr;
1040 }
1041
1042 void swiotlb_free(struct device *dev, size_t size, void *vaddr,
1043                 dma_addr_t dma_addr, unsigned long attrs)
1044 {
1045         if (!swiotlb_free_buffer(dev, size, dma_addr))
1046                 dma_direct_free(dev, size, vaddr, dma_addr, attrs);
1047 }
1048
1049 const struct dma_map_ops swiotlb_dma_ops = {
1050         .mapping_error          = swiotlb_dma_mapping_error,
1051         .alloc                  = swiotlb_alloc,
1052         .free                   = swiotlb_free,
1053         .sync_single_for_cpu    = swiotlb_sync_single_for_cpu,
1054         .sync_single_for_device = swiotlb_sync_single_for_device,
1055         .sync_sg_for_cpu        = swiotlb_sync_sg_for_cpu,
1056         .sync_sg_for_device     = swiotlb_sync_sg_for_device,
1057         .map_sg                 = swiotlb_map_sg_attrs,
1058         .unmap_sg               = swiotlb_unmap_sg_attrs,
1059         .map_page               = swiotlb_map_page,
1060         .unmap_page             = swiotlb_unmap_page,
1061         .dma_supported          = dma_direct_supported,
1062 };
1063 EXPORT_SYMBOL(swiotlb_dma_ops);