GNU Linux-libre 5.4.241-gnu1
[releases.git] / drivers / iommu / dma-iommu.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * A fairly generic DMA-API to IOMMU-API glue layer.
4  *
5  * Copyright (C) 2014-2015 ARM Ltd.
6  *
7  * based in part on arch/arm/mm/dma-mapping.c:
8  * Copyright (C) 2000-2004 Russell King
9  */
10
11 #include <linux/acpi_iort.h>
12 #include <linux/device.h>
13 #include <linux/dma-contiguous.h>
14 #include <linux/dma-iommu.h>
15 #include <linux/dma-noncoherent.h>
16 #include <linux/gfp.h>
17 #include <linux/huge_mm.h>
18 #include <linux/iommu.h>
19 #include <linux/iova.h>
20 #include <linux/irq.h>
21 #include <linux/mm.h>
22 #include <linux/mutex.h>
23 #include <linux/pci.h>
24 #include <linux/scatterlist.h>
25 #include <linux/vmalloc.h>
26
27 struct iommu_dma_msi_page {
28         struct list_head        list;
29         dma_addr_t              iova;
30         phys_addr_t             phys;
31 };
32
33 enum iommu_dma_cookie_type {
34         IOMMU_DMA_IOVA_COOKIE,
35         IOMMU_DMA_MSI_COOKIE,
36 };
37
38 struct iommu_dma_cookie {
39         enum iommu_dma_cookie_type      type;
40         union {
41                 /* Full allocator for IOMMU_DMA_IOVA_COOKIE */
42                 struct iova_domain      iovad;
43                 /* Trivial linear page allocator for IOMMU_DMA_MSI_COOKIE */
44                 dma_addr_t              msi_iova;
45         };
46         struct list_head                msi_page_list;
47
48         /* Domain for flush queue callback; NULL if flush queue not in use */
49         struct iommu_domain             *fq_domain;
50 };
51
52 static inline size_t cookie_msi_granule(struct iommu_dma_cookie *cookie)
53 {
54         if (cookie->type == IOMMU_DMA_IOVA_COOKIE)
55                 return cookie->iovad.granule;
56         return PAGE_SIZE;
57 }
58
59 static struct iommu_dma_cookie *cookie_alloc(enum iommu_dma_cookie_type type)
60 {
61         struct iommu_dma_cookie *cookie;
62
63         cookie = kzalloc(sizeof(*cookie), GFP_KERNEL);
64         if (cookie) {
65                 INIT_LIST_HEAD(&cookie->msi_page_list);
66                 cookie->type = type;
67         }
68         return cookie;
69 }
70
71 /**
72  * iommu_get_dma_cookie - Acquire DMA-API resources for a domain
73  * @domain: IOMMU domain to prepare for DMA-API usage
74  *
75  * IOMMU drivers should normally call this from their domain_alloc
76  * callback when domain->type == IOMMU_DOMAIN_DMA.
77  */
78 int iommu_get_dma_cookie(struct iommu_domain *domain)
79 {
80         if (domain->iova_cookie)
81                 return -EEXIST;
82
83         domain->iova_cookie = cookie_alloc(IOMMU_DMA_IOVA_COOKIE);
84         if (!domain->iova_cookie)
85                 return -ENOMEM;
86
87         return 0;
88 }
89 EXPORT_SYMBOL(iommu_get_dma_cookie);
90
91 /**
92  * iommu_get_msi_cookie - Acquire just MSI remapping resources
93  * @domain: IOMMU domain to prepare
94  * @base: Start address of IOVA region for MSI mappings
95  *
96  * Users who manage their own IOVA allocation and do not want DMA API support,
97  * but would still like to take advantage of automatic MSI remapping, can use
98  * this to initialise their own domain appropriately. Users should reserve a
99  * contiguous IOVA region, starting at @base, large enough to accommodate the
100  * number of PAGE_SIZE mappings necessary to cover every MSI doorbell address
101  * used by the devices attached to @domain.
102  */
103 int iommu_get_msi_cookie(struct iommu_domain *domain, dma_addr_t base)
104 {
105         struct iommu_dma_cookie *cookie;
106
107         if (domain->type != IOMMU_DOMAIN_UNMANAGED)
108                 return -EINVAL;
109
110         if (domain->iova_cookie)
111                 return -EEXIST;
112
113         cookie = cookie_alloc(IOMMU_DMA_MSI_COOKIE);
114         if (!cookie)
115                 return -ENOMEM;
116
117         cookie->msi_iova = base;
118         domain->iova_cookie = cookie;
119         return 0;
120 }
121 EXPORT_SYMBOL(iommu_get_msi_cookie);
122
123 /**
124  * iommu_put_dma_cookie - Release a domain's DMA mapping resources
125  * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie() or
126  *          iommu_get_msi_cookie()
127  *
128  * IOMMU drivers should normally call this from their domain_free callback.
129  */
130 void iommu_put_dma_cookie(struct iommu_domain *domain)
131 {
132         struct iommu_dma_cookie *cookie = domain->iova_cookie;
133         struct iommu_dma_msi_page *msi, *tmp;
134
135         if (!cookie)
136                 return;
137
138         if (cookie->type == IOMMU_DMA_IOVA_COOKIE && cookie->iovad.granule)
139                 put_iova_domain(&cookie->iovad);
140
141         list_for_each_entry_safe(msi, tmp, &cookie->msi_page_list, list) {
142                 list_del(&msi->list);
143                 kfree(msi);
144         }
145         kfree(cookie);
146         domain->iova_cookie = NULL;
147 }
148 EXPORT_SYMBOL(iommu_put_dma_cookie);
149
150 /**
151  * iommu_dma_get_resv_regions - Reserved region driver helper
152  * @dev: Device from iommu_get_resv_regions()
153  * @list: Reserved region list from iommu_get_resv_regions()
154  *
155  * IOMMU drivers can use this to implement their .get_resv_regions callback
156  * for general non-IOMMU-specific reservations. Currently, this covers GICv3
157  * ITS region reservation on ACPI based ARM platforms that may require HW MSI
158  * reservation.
159  */
160 void iommu_dma_get_resv_regions(struct device *dev, struct list_head *list)
161 {
162
163         if (!is_of_node(dev_iommu_fwspec_get(dev)->iommu_fwnode))
164                 iort_iommu_msi_get_resv_regions(dev, list);
165
166 }
167 EXPORT_SYMBOL(iommu_dma_get_resv_regions);
168
169 static int cookie_init_hw_msi_region(struct iommu_dma_cookie *cookie,
170                 phys_addr_t start, phys_addr_t end)
171 {
172         struct iova_domain *iovad = &cookie->iovad;
173         struct iommu_dma_msi_page *msi_page;
174         int i, num_pages;
175
176         start -= iova_offset(iovad, start);
177         num_pages = iova_align(iovad, end - start) >> iova_shift(iovad);
178
179         for (i = 0; i < num_pages; i++) {
180                 msi_page = kmalloc(sizeof(*msi_page), GFP_KERNEL);
181                 if (!msi_page)
182                         return -ENOMEM;
183
184                 msi_page->phys = start;
185                 msi_page->iova = start;
186                 INIT_LIST_HEAD(&msi_page->list);
187                 list_add(&msi_page->list, &cookie->msi_page_list);
188                 start += iovad->granule;
189         }
190
191         return 0;
192 }
193
194 static int iova_reserve_pci_windows(struct pci_dev *dev,
195                 struct iova_domain *iovad)
196 {
197         struct pci_host_bridge *bridge = pci_find_host_bridge(dev->bus);
198         struct resource_entry *window;
199         unsigned long lo, hi;
200         phys_addr_t start = 0, end;
201
202         resource_list_for_each_entry(window, &bridge->windows) {
203                 if (resource_type(window->res) != IORESOURCE_MEM)
204                         continue;
205
206                 lo = iova_pfn(iovad, window->res->start - window->offset);
207                 hi = iova_pfn(iovad, window->res->end - window->offset);
208                 reserve_iova(iovad, lo, hi);
209         }
210
211         /* Get reserved DMA windows from host bridge */
212         resource_list_for_each_entry(window, &bridge->dma_ranges) {
213                 end = window->res->start - window->offset;
214 resv_iova:
215                 if (end > start) {
216                         lo = iova_pfn(iovad, start);
217                         hi = iova_pfn(iovad, end);
218                         reserve_iova(iovad, lo, hi);
219                 } else if (end < start) {
220                         /* dma_ranges list should be sorted */
221                         dev_err(&dev->dev,
222                                 "Failed to reserve IOVA [%pa-%pa]\n",
223                                 &start, &end);
224                         return -EINVAL;
225                 }
226
227                 start = window->res->end - window->offset + 1;
228                 /* If window is last entry */
229                 if (window->node.next == &bridge->dma_ranges &&
230                     end != ~(phys_addr_t)0) {
231                         end = ~(phys_addr_t)0;
232                         goto resv_iova;
233                 }
234         }
235
236         return 0;
237 }
238
239 static int iova_reserve_iommu_regions(struct device *dev,
240                 struct iommu_domain *domain)
241 {
242         struct iommu_dma_cookie *cookie = domain->iova_cookie;
243         struct iova_domain *iovad = &cookie->iovad;
244         struct iommu_resv_region *region;
245         LIST_HEAD(resv_regions);
246         int ret = 0;
247
248         if (dev_is_pci(dev)) {
249                 ret = iova_reserve_pci_windows(to_pci_dev(dev), iovad);
250                 if (ret)
251                         return ret;
252         }
253
254         iommu_get_resv_regions(dev, &resv_regions);
255         list_for_each_entry(region, &resv_regions, list) {
256                 unsigned long lo, hi;
257
258                 /* We ARE the software that manages these! */
259                 if (region->type == IOMMU_RESV_SW_MSI)
260                         continue;
261
262                 lo = iova_pfn(iovad, region->start);
263                 hi = iova_pfn(iovad, region->start + region->length - 1);
264                 reserve_iova(iovad, lo, hi);
265
266                 if (region->type == IOMMU_RESV_MSI)
267                         ret = cookie_init_hw_msi_region(cookie, region->start,
268                                         region->start + region->length);
269                 if (ret)
270                         break;
271         }
272         iommu_put_resv_regions(dev, &resv_regions);
273
274         return ret;
275 }
276
277 static void iommu_dma_flush_iotlb_all(struct iova_domain *iovad)
278 {
279         struct iommu_dma_cookie *cookie;
280         struct iommu_domain *domain;
281
282         cookie = container_of(iovad, struct iommu_dma_cookie, iovad);
283         domain = cookie->fq_domain;
284         /*
285          * The IOMMU driver supporting DOMAIN_ATTR_DMA_USE_FLUSH_QUEUE
286          * implies that ops->flush_iotlb_all must be non-NULL.
287          */
288         domain->ops->flush_iotlb_all(domain);
289 }
290
291 /**
292  * iommu_dma_init_domain - Initialise a DMA mapping domain
293  * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie()
294  * @base: IOVA at which the mappable address space starts
295  * @size: Size of IOVA space
296  * @dev: Device the domain is being initialised for
297  *
298  * @base and @size should be exact multiples of IOMMU page granularity to
299  * avoid rounding surprises. If necessary, we reserve the page at address 0
300  * to ensure it is an invalid IOVA. It is safe to reinitialise a domain, but
301  * any change which could make prior IOVAs invalid will fail.
302  */
303 static int iommu_dma_init_domain(struct iommu_domain *domain, dma_addr_t base,
304                 u64 size, struct device *dev)
305 {
306         struct iommu_dma_cookie *cookie = domain->iova_cookie;
307         unsigned long order, base_pfn;
308         struct iova_domain *iovad;
309         int attr;
310
311         if (!cookie || cookie->type != IOMMU_DMA_IOVA_COOKIE)
312                 return -EINVAL;
313
314         iovad = &cookie->iovad;
315
316         /* Use the smallest supported page size for IOVA granularity */
317         order = __ffs(domain->pgsize_bitmap);
318         base_pfn = max_t(unsigned long, 1, base >> order);
319
320         /* Check the domain allows at least some access to the device... */
321         if (domain->geometry.force_aperture) {
322                 if (base > domain->geometry.aperture_end ||
323                     base + size <= domain->geometry.aperture_start) {
324                         pr_warn("specified DMA range outside IOMMU capability\n");
325                         return -EFAULT;
326                 }
327                 /* ...then finally give it a kicking to make sure it fits */
328                 base_pfn = max_t(unsigned long, base_pfn,
329                                 domain->geometry.aperture_start >> order);
330         }
331
332         /* start_pfn is always nonzero for an already-initialised domain */
333         if (iovad->start_pfn) {
334                 if (1UL << order != iovad->granule ||
335                     base_pfn != iovad->start_pfn) {
336                         pr_warn("Incompatible range for DMA domain\n");
337                         return -EFAULT;
338                 }
339
340                 return 0;
341         }
342
343         init_iova_domain(iovad, 1UL << order, base_pfn);
344
345         if (!cookie->fq_domain && !iommu_domain_get_attr(domain,
346                         DOMAIN_ATTR_DMA_USE_FLUSH_QUEUE, &attr) && attr) {
347                 cookie->fq_domain = domain;
348                 init_iova_flush_queue(iovad, iommu_dma_flush_iotlb_all, NULL);
349         }
350
351         if (!dev)
352                 return 0;
353
354         return iova_reserve_iommu_regions(dev, domain);
355 }
356
357 /**
358  * dma_info_to_prot - Translate DMA API directions and attributes to IOMMU API
359  *                    page flags.
360  * @dir: Direction of DMA transfer
361  * @coherent: Is the DMA master cache-coherent?
362  * @attrs: DMA attributes for the mapping
363  *
364  * Return: corresponding IOMMU API page protection flags
365  */
366 static int dma_info_to_prot(enum dma_data_direction dir, bool coherent,
367                      unsigned long attrs)
368 {
369         int prot = coherent ? IOMMU_CACHE : 0;
370
371         if (attrs & DMA_ATTR_PRIVILEGED)
372                 prot |= IOMMU_PRIV;
373
374         switch (dir) {
375         case DMA_BIDIRECTIONAL:
376                 return prot | IOMMU_READ | IOMMU_WRITE;
377         case DMA_TO_DEVICE:
378                 return prot | IOMMU_READ;
379         case DMA_FROM_DEVICE:
380                 return prot | IOMMU_WRITE;
381         default:
382                 return 0;
383         }
384 }
385
386 static dma_addr_t iommu_dma_alloc_iova(struct iommu_domain *domain,
387                 size_t size, dma_addr_t dma_limit, struct device *dev)
388 {
389         struct iommu_dma_cookie *cookie = domain->iova_cookie;
390         struct iova_domain *iovad = &cookie->iovad;
391         unsigned long shift, iova_len, iova = 0;
392
393         if (cookie->type == IOMMU_DMA_MSI_COOKIE) {
394                 cookie->msi_iova += size;
395                 return cookie->msi_iova - size;
396         }
397
398         shift = iova_shift(iovad);
399         iova_len = size >> shift;
400         /*
401          * Freeing non-power-of-two-sized allocations back into the IOVA caches
402          * will come back to bite us badly, so we have to waste a bit of space
403          * rounding up anything cacheable to make sure that can't happen. The
404          * order of the unadjusted size will still match upon freeing.
405          */
406         if (iova_len < (1 << (IOVA_RANGE_CACHE_MAX_SIZE - 1)))
407                 iova_len = roundup_pow_of_two(iova_len);
408
409         if (dev->bus_dma_mask)
410                 dma_limit &= dev->bus_dma_mask;
411
412         if (domain->geometry.force_aperture)
413                 dma_limit = min(dma_limit, domain->geometry.aperture_end);
414
415         /* Try to get PCI devices a SAC address */
416         if (dma_limit > DMA_BIT_MASK(32) && dev_is_pci(dev))
417                 iova = alloc_iova_fast(iovad, iova_len,
418                                        DMA_BIT_MASK(32) >> shift, false);
419
420         if (!iova)
421                 iova = alloc_iova_fast(iovad, iova_len, dma_limit >> shift,
422                                        true);
423
424         return (dma_addr_t)iova << shift;
425 }
426
427 static void iommu_dma_free_iova(struct iommu_dma_cookie *cookie,
428                 dma_addr_t iova, size_t size)
429 {
430         struct iova_domain *iovad = &cookie->iovad;
431
432         /* The MSI case is only ever cleaning up its most recent allocation */
433         if (cookie->type == IOMMU_DMA_MSI_COOKIE)
434                 cookie->msi_iova -= size;
435         else if (cookie->fq_domain)     /* non-strict mode */
436                 queue_iova(iovad, iova_pfn(iovad, iova),
437                                 size >> iova_shift(iovad), 0);
438         else
439                 free_iova_fast(iovad, iova_pfn(iovad, iova),
440                                 size >> iova_shift(iovad));
441 }
442
443 static void __iommu_dma_unmap(struct device *dev, dma_addr_t dma_addr,
444                 size_t size)
445 {
446         struct iommu_domain *domain = iommu_get_dma_domain(dev);
447         struct iommu_dma_cookie *cookie = domain->iova_cookie;
448         struct iova_domain *iovad = &cookie->iovad;
449         size_t iova_off = iova_offset(iovad, dma_addr);
450         struct iommu_iotlb_gather iotlb_gather;
451         size_t unmapped;
452
453         dma_addr -= iova_off;
454         size = iova_align(iovad, size + iova_off);
455         iommu_iotlb_gather_init(&iotlb_gather);
456
457         unmapped = iommu_unmap_fast(domain, dma_addr, size, &iotlb_gather);
458         WARN_ON(unmapped != size);
459
460         if (!cookie->fq_domain)
461                 iommu_tlb_sync(domain, &iotlb_gather);
462         iommu_dma_free_iova(cookie, dma_addr, size);
463 }
464
465 static dma_addr_t __iommu_dma_map(struct device *dev, phys_addr_t phys,
466                 size_t size, int prot)
467 {
468         struct iommu_domain *domain = iommu_get_dma_domain(dev);
469         struct iommu_dma_cookie *cookie = domain->iova_cookie;
470         struct iova_domain *iovad = &cookie->iovad;
471         size_t iova_off = iova_offset(iovad, phys);
472         dma_addr_t iova;
473
474         size = iova_align(iovad, size + iova_off);
475
476         iova = iommu_dma_alloc_iova(domain, size, dma_get_mask(dev), dev);
477         if (!iova)
478                 return DMA_MAPPING_ERROR;
479
480         if (iommu_map_atomic(domain, iova, phys - iova_off, size, prot)) {
481                 iommu_dma_free_iova(cookie, iova, size);
482                 return DMA_MAPPING_ERROR;
483         }
484         return iova + iova_off;
485 }
486
487 static void __iommu_dma_free_pages(struct page **pages, int count)
488 {
489         while (count--)
490                 __free_page(pages[count]);
491         kvfree(pages);
492 }
493
494 static struct page **__iommu_dma_alloc_pages(struct device *dev,
495                 unsigned int count, unsigned long order_mask, gfp_t gfp)
496 {
497         struct page **pages;
498         unsigned int i = 0, nid = dev_to_node(dev);
499
500         order_mask &= (2U << MAX_ORDER) - 1;
501         if (!order_mask)
502                 return NULL;
503
504         pages = kvzalloc(count * sizeof(*pages), GFP_KERNEL);
505         if (!pages)
506                 return NULL;
507
508         /* IOMMU can map any pages, so himem can also be used here */
509         gfp |= __GFP_NOWARN | __GFP_HIGHMEM;
510
511         while (count) {
512                 struct page *page = NULL;
513                 unsigned int order_size;
514
515                 /*
516                  * Higher-order allocations are a convenience rather
517                  * than a necessity, hence using __GFP_NORETRY until
518                  * falling back to minimum-order allocations.
519                  */
520                 for (order_mask &= (2U << __fls(count)) - 1;
521                      order_mask; order_mask &= ~order_size) {
522                         unsigned int order = __fls(order_mask);
523                         gfp_t alloc_flags = gfp;
524
525                         order_size = 1U << order;
526                         if (order_mask > order_size)
527                                 alloc_flags |= __GFP_NORETRY;
528                         page = alloc_pages_node(nid, alloc_flags, order);
529                         if (!page)
530                                 continue;
531                         if (!order)
532                                 break;
533                         if (!PageCompound(page)) {
534                                 split_page(page, order);
535                                 break;
536                         } else if (!split_huge_page(page)) {
537                                 break;
538                         }
539                         __free_pages(page, order);
540                 }
541                 if (!page) {
542                         __iommu_dma_free_pages(pages, i);
543                         return NULL;
544                 }
545                 count -= order_size;
546                 while (order_size--)
547                         pages[i++] = page++;
548         }
549         return pages;
550 }
551
552 /**
553  * iommu_dma_alloc_remap - Allocate and map a buffer contiguous in IOVA space
554  * @dev: Device to allocate memory for. Must be a real device
555  *       attached to an iommu_dma_domain
556  * @size: Size of buffer in bytes
557  * @dma_handle: Out argument for allocated DMA handle
558  * @gfp: Allocation flags
559  * @attrs: DMA attributes for this allocation
560  *
561  * If @size is less than PAGE_SIZE, then a full CPU page will be allocated,
562  * but an IOMMU which supports smaller pages might not map the whole thing.
563  *
564  * Return: Mapped virtual address, or NULL on failure.
565  */
566 static void *iommu_dma_alloc_remap(struct device *dev, size_t size,
567                 dma_addr_t *dma_handle, gfp_t gfp, unsigned long attrs)
568 {
569         struct iommu_domain *domain = iommu_get_dma_domain(dev);
570         struct iommu_dma_cookie *cookie = domain->iova_cookie;
571         struct iova_domain *iovad = &cookie->iovad;
572         bool coherent = dev_is_dma_coherent(dev);
573         int ioprot = dma_info_to_prot(DMA_BIDIRECTIONAL, coherent, attrs);
574         pgprot_t prot = dma_pgprot(dev, PAGE_KERNEL, attrs);
575         unsigned int count, min_size, alloc_sizes = domain->pgsize_bitmap;
576         struct page **pages;
577         struct sg_table sgt;
578         dma_addr_t iova;
579         void *vaddr;
580
581         *dma_handle = DMA_MAPPING_ERROR;
582
583         min_size = alloc_sizes & -alloc_sizes;
584         if (min_size < PAGE_SIZE) {
585                 min_size = PAGE_SIZE;
586                 alloc_sizes |= PAGE_SIZE;
587         } else {
588                 size = ALIGN(size, min_size);
589         }
590         if (attrs & DMA_ATTR_ALLOC_SINGLE_PAGES)
591                 alloc_sizes = min_size;
592
593         count = PAGE_ALIGN(size) >> PAGE_SHIFT;
594         pages = __iommu_dma_alloc_pages(dev, count, alloc_sizes >> PAGE_SHIFT,
595                                         gfp);
596         if (!pages)
597                 return NULL;
598
599         size = iova_align(iovad, size);
600         iova = iommu_dma_alloc_iova(domain, size, dev->coherent_dma_mask, dev);
601         if (!iova)
602                 goto out_free_pages;
603
604         if (sg_alloc_table_from_pages(&sgt, pages, count, 0, size, GFP_KERNEL))
605                 goto out_free_iova;
606
607         if (!(ioprot & IOMMU_CACHE)) {
608                 struct scatterlist *sg;
609                 int i;
610
611                 for_each_sg(sgt.sgl, sg, sgt.orig_nents, i)
612                         arch_dma_prep_coherent(sg_page(sg), sg->length);
613         }
614
615         if (iommu_map_sg_atomic(domain, iova, sgt.sgl, sgt.orig_nents, ioprot)
616                         < size)
617                 goto out_free_sg;
618
619         vaddr = dma_common_pages_remap(pages, size, prot,
620                         __builtin_return_address(0));
621         if (!vaddr)
622                 goto out_unmap;
623
624         *dma_handle = iova;
625         sg_free_table(&sgt);
626         return vaddr;
627
628 out_unmap:
629         __iommu_dma_unmap(dev, iova, size);
630 out_free_sg:
631         sg_free_table(&sgt);
632 out_free_iova:
633         iommu_dma_free_iova(cookie, iova, size);
634 out_free_pages:
635         __iommu_dma_free_pages(pages, count);
636         return NULL;
637 }
638
639 /**
640  * __iommu_dma_mmap - Map a buffer into provided user VMA
641  * @pages: Array representing buffer from __iommu_dma_alloc()
642  * @size: Size of buffer in bytes
643  * @vma: VMA describing requested userspace mapping
644  *
645  * Maps the pages of the buffer in @pages into @vma. The caller is responsible
646  * for verifying the correct size and protection of @vma beforehand.
647  */
648 static int __iommu_dma_mmap(struct page **pages, size_t size,
649                 struct vm_area_struct *vma)
650 {
651         return vm_map_pages(vma, pages, PAGE_ALIGN(size) >> PAGE_SHIFT);
652 }
653
654 static void iommu_dma_sync_single_for_cpu(struct device *dev,
655                 dma_addr_t dma_handle, size_t size, enum dma_data_direction dir)
656 {
657         phys_addr_t phys;
658
659         if (dev_is_dma_coherent(dev))
660                 return;
661
662         phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle);
663         arch_sync_dma_for_cpu(phys, size, dir);
664 }
665
666 static void iommu_dma_sync_single_for_device(struct device *dev,
667                 dma_addr_t dma_handle, size_t size, enum dma_data_direction dir)
668 {
669         phys_addr_t phys;
670
671         if (dev_is_dma_coherent(dev))
672                 return;
673
674         phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle);
675         arch_sync_dma_for_device(phys, size, dir);
676 }
677
678 static void iommu_dma_sync_sg_for_cpu(struct device *dev,
679                 struct scatterlist *sgl, int nelems,
680                 enum dma_data_direction dir)
681 {
682         struct scatterlist *sg;
683         int i;
684
685         if (dev_is_dma_coherent(dev))
686                 return;
687
688         for_each_sg(sgl, sg, nelems, i)
689                 arch_sync_dma_for_cpu(sg_phys(sg), sg->length, dir);
690 }
691
692 static void iommu_dma_sync_sg_for_device(struct device *dev,
693                 struct scatterlist *sgl, int nelems,
694                 enum dma_data_direction dir)
695 {
696         struct scatterlist *sg;
697         int i;
698
699         if (dev_is_dma_coherent(dev))
700                 return;
701
702         for_each_sg(sgl, sg, nelems, i)
703                 arch_sync_dma_for_device(sg_phys(sg), sg->length, dir);
704 }
705
706 static dma_addr_t iommu_dma_map_page(struct device *dev, struct page *page,
707                 unsigned long offset, size_t size, enum dma_data_direction dir,
708                 unsigned long attrs)
709 {
710         phys_addr_t phys = page_to_phys(page) + offset;
711         bool coherent = dev_is_dma_coherent(dev);
712         int prot = dma_info_to_prot(dir, coherent, attrs);
713         dma_addr_t dma_handle;
714
715         dma_handle =__iommu_dma_map(dev, phys, size, prot);
716         if (!coherent && !(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
717             dma_handle != DMA_MAPPING_ERROR)
718                 arch_sync_dma_for_device(phys, size, dir);
719         return dma_handle;
720 }
721
722 static void iommu_dma_unmap_page(struct device *dev, dma_addr_t dma_handle,
723                 size_t size, enum dma_data_direction dir, unsigned long attrs)
724 {
725         if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
726                 iommu_dma_sync_single_for_cpu(dev, dma_handle, size, dir);
727         __iommu_dma_unmap(dev, dma_handle, size);
728 }
729
730 /*
731  * Prepare a successfully-mapped scatterlist to give back to the caller.
732  *
733  * At this point the segments are already laid out by iommu_dma_map_sg() to
734  * avoid individually crossing any boundaries, so we merely need to check a
735  * segment's start address to avoid concatenating across one.
736  */
737 static int __finalise_sg(struct device *dev, struct scatterlist *sg, int nents,
738                 dma_addr_t dma_addr)
739 {
740         struct scatterlist *s, *cur = sg;
741         unsigned long seg_mask = dma_get_seg_boundary(dev);
742         unsigned int cur_len = 0, max_len = dma_get_max_seg_size(dev);
743         int i, count = 0;
744
745         for_each_sg(sg, s, nents, i) {
746                 /* Restore this segment's original unaligned fields first */
747                 unsigned int s_iova_off = sg_dma_address(s);
748                 unsigned int s_length = sg_dma_len(s);
749                 unsigned int s_iova_len = s->length;
750
751                 s->offset += s_iova_off;
752                 s->length = s_length;
753                 sg_dma_address(s) = DMA_MAPPING_ERROR;
754                 sg_dma_len(s) = 0;
755
756                 /*
757                  * Now fill in the real DMA data. If...
758                  * - there is a valid output segment to append to
759                  * - and this segment starts on an IOVA page boundary
760                  * - but doesn't fall at a segment boundary
761                  * - and wouldn't make the resulting output segment too long
762                  */
763                 if (cur_len && !s_iova_off && (dma_addr & seg_mask) &&
764                     (max_len - cur_len >= s_length)) {
765                         /* ...then concatenate it with the previous one */
766                         cur_len += s_length;
767                 } else {
768                         /* Otherwise start the next output segment */
769                         if (i > 0)
770                                 cur = sg_next(cur);
771                         cur_len = s_length;
772                         count++;
773
774                         sg_dma_address(cur) = dma_addr + s_iova_off;
775                 }
776
777                 sg_dma_len(cur) = cur_len;
778                 dma_addr += s_iova_len;
779
780                 if (s_length + s_iova_off < s_iova_len)
781                         cur_len = 0;
782         }
783         return count;
784 }
785
786 /*
787  * If mapping failed, then just restore the original list,
788  * but making sure the DMA fields are invalidated.
789  */
790 static void __invalidate_sg(struct scatterlist *sg, int nents)
791 {
792         struct scatterlist *s;
793         int i;
794
795         for_each_sg(sg, s, nents, i) {
796                 if (sg_dma_address(s) != DMA_MAPPING_ERROR)
797                         s->offset += sg_dma_address(s);
798                 if (sg_dma_len(s))
799                         s->length = sg_dma_len(s);
800                 sg_dma_address(s) = DMA_MAPPING_ERROR;
801                 sg_dma_len(s) = 0;
802         }
803 }
804
805 /*
806  * The DMA API client is passing in a scatterlist which could describe
807  * any old buffer layout, but the IOMMU API requires everything to be
808  * aligned to IOMMU pages. Hence the need for this complicated bit of
809  * impedance-matching, to be able to hand off a suitably-aligned list,
810  * but still preserve the original offsets and sizes for the caller.
811  */
812 static int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg,
813                 int nents, enum dma_data_direction dir, unsigned long attrs)
814 {
815         struct iommu_domain *domain = iommu_get_dma_domain(dev);
816         struct iommu_dma_cookie *cookie = domain->iova_cookie;
817         struct iova_domain *iovad = &cookie->iovad;
818         struct scatterlist *s, *prev = NULL;
819         int prot = dma_info_to_prot(dir, dev_is_dma_coherent(dev), attrs);
820         dma_addr_t iova;
821         size_t iova_len = 0;
822         unsigned long mask = dma_get_seg_boundary(dev);
823         int i;
824
825         if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
826                 iommu_dma_sync_sg_for_device(dev, sg, nents, dir);
827
828         /*
829          * Work out how much IOVA space we need, and align the segments to
830          * IOVA granules for the IOMMU driver to handle. With some clever
831          * trickery we can modify the list in-place, but reversibly, by
832          * stashing the unaligned parts in the as-yet-unused DMA fields.
833          */
834         for_each_sg(sg, s, nents, i) {
835                 size_t s_iova_off = iova_offset(iovad, s->offset);
836                 size_t s_length = s->length;
837                 size_t pad_len = (mask - iova_len + 1) & mask;
838
839                 sg_dma_address(s) = s_iova_off;
840                 sg_dma_len(s) = s_length;
841                 s->offset -= s_iova_off;
842                 s_length = iova_align(iovad, s_length + s_iova_off);
843                 s->length = s_length;
844
845                 /*
846                  * Due to the alignment of our single IOVA allocation, we can
847                  * depend on these assumptions about the segment boundary mask:
848                  * - If mask size >= IOVA size, then the IOVA range cannot
849                  *   possibly fall across a boundary, so we don't care.
850                  * - If mask size < IOVA size, then the IOVA range must start
851                  *   exactly on a boundary, therefore we can lay things out
852                  *   based purely on segment lengths without needing to know
853                  *   the actual addresses beforehand.
854                  * - The mask must be a power of 2, so pad_len == 0 if
855                  *   iova_len == 0, thus we cannot dereference prev the first
856                  *   time through here (i.e. before it has a meaningful value).
857                  */
858                 if (pad_len && pad_len < s_length - 1) {
859                         prev->length += pad_len;
860                         iova_len += pad_len;
861                 }
862
863                 iova_len += s_length;
864                 prev = s;
865         }
866
867         iova = iommu_dma_alloc_iova(domain, iova_len, dma_get_mask(dev), dev);
868         if (!iova)
869                 goto out_restore_sg;
870
871         /*
872          * We'll leave any physical concatenation to the IOMMU driver's
873          * implementation - it knows better than we do.
874          */
875         if (iommu_map_sg_atomic(domain, iova, sg, nents, prot) < iova_len)
876                 goto out_free_iova;
877
878         return __finalise_sg(dev, sg, nents, iova);
879
880 out_free_iova:
881         iommu_dma_free_iova(cookie, iova, iova_len);
882 out_restore_sg:
883         __invalidate_sg(sg, nents);
884         return 0;
885 }
886
887 static void iommu_dma_unmap_sg(struct device *dev, struct scatterlist *sg,
888                 int nents, enum dma_data_direction dir, unsigned long attrs)
889 {
890         dma_addr_t start, end;
891         struct scatterlist *tmp;
892         int i;
893
894         if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
895                 iommu_dma_sync_sg_for_cpu(dev, sg, nents, dir);
896
897         /*
898          * The scatterlist segments are mapped into a single
899          * contiguous IOVA allocation, so this is incredibly easy.
900          */
901         start = sg_dma_address(sg);
902         for_each_sg(sg_next(sg), tmp, nents - 1, i) {
903                 if (sg_dma_len(tmp) == 0)
904                         break;
905                 sg = tmp;
906         }
907         end = sg_dma_address(sg) + sg_dma_len(sg);
908         __iommu_dma_unmap(dev, start, end - start);
909 }
910
911 static dma_addr_t iommu_dma_map_resource(struct device *dev, phys_addr_t phys,
912                 size_t size, enum dma_data_direction dir, unsigned long attrs)
913 {
914         return __iommu_dma_map(dev, phys, size,
915                         dma_info_to_prot(dir, false, attrs) | IOMMU_MMIO);
916 }
917
918 static void iommu_dma_unmap_resource(struct device *dev, dma_addr_t handle,
919                 size_t size, enum dma_data_direction dir, unsigned long attrs)
920 {
921         __iommu_dma_unmap(dev, handle, size);
922 }
923
924 static void __iommu_dma_free(struct device *dev, size_t size, void *cpu_addr)
925 {
926         size_t alloc_size = PAGE_ALIGN(size);
927         int count = alloc_size >> PAGE_SHIFT;
928         struct page *page = NULL, **pages = NULL;
929
930         /* Non-coherent atomic allocation? Easy */
931         if (IS_ENABLED(CONFIG_DMA_DIRECT_REMAP) &&
932             dma_free_from_pool(cpu_addr, alloc_size))
933                 return;
934
935         if (IS_ENABLED(CONFIG_DMA_REMAP) && is_vmalloc_addr(cpu_addr)) {
936                 /*
937                  * If it the address is remapped, then it's either non-coherent
938                  * or highmem CMA, or an iommu_dma_alloc_remap() construction.
939                  */
940                 pages = dma_common_find_pages(cpu_addr);
941                 if (!pages)
942                         page = vmalloc_to_page(cpu_addr);
943                 dma_common_free_remap(cpu_addr, alloc_size);
944         } else {
945                 /* Lowmem means a coherent atomic or CMA allocation */
946                 page = virt_to_page(cpu_addr);
947         }
948
949         if (pages)
950                 __iommu_dma_free_pages(pages, count);
951         if (page)
952                 dma_free_contiguous(dev, page, alloc_size);
953 }
954
955 static void iommu_dma_free(struct device *dev, size_t size, void *cpu_addr,
956                 dma_addr_t handle, unsigned long attrs)
957 {
958         __iommu_dma_unmap(dev, handle, size);
959         __iommu_dma_free(dev, size, cpu_addr);
960 }
961
962 static void *iommu_dma_alloc_pages(struct device *dev, size_t size,
963                 struct page **pagep, gfp_t gfp, unsigned long attrs)
964 {
965         bool coherent = dev_is_dma_coherent(dev);
966         size_t alloc_size = PAGE_ALIGN(size);
967         int node = dev_to_node(dev);
968         struct page *page = NULL;
969         void *cpu_addr;
970
971         page = dma_alloc_contiguous(dev, alloc_size, gfp);
972         if (!page)
973                 page = alloc_pages_node(node, gfp, get_order(alloc_size));
974         if (!page)
975                 return NULL;
976
977         if (IS_ENABLED(CONFIG_DMA_REMAP) && (!coherent || PageHighMem(page))) {
978                 pgprot_t prot = dma_pgprot(dev, PAGE_KERNEL, attrs);
979
980                 cpu_addr = dma_common_contiguous_remap(page, alloc_size,
981                                 prot, __builtin_return_address(0));
982                 if (!cpu_addr)
983                         goto out_free_pages;
984
985                 if (!coherent)
986                         arch_dma_prep_coherent(page, size);
987         } else {
988                 cpu_addr = page_address(page);
989         }
990
991         *pagep = page;
992         memset(cpu_addr, 0, alloc_size);
993         return cpu_addr;
994 out_free_pages:
995         dma_free_contiguous(dev, page, alloc_size);
996         return NULL;
997 }
998
999 static void *iommu_dma_alloc(struct device *dev, size_t size,
1000                 dma_addr_t *handle, gfp_t gfp, unsigned long attrs)
1001 {
1002         bool coherent = dev_is_dma_coherent(dev);
1003         int ioprot = dma_info_to_prot(DMA_BIDIRECTIONAL, coherent, attrs);
1004         struct page *page = NULL;
1005         void *cpu_addr;
1006
1007         gfp |= __GFP_ZERO;
1008
1009         if (IS_ENABLED(CONFIG_DMA_REMAP) && gfpflags_allow_blocking(gfp) &&
1010             !(attrs & DMA_ATTR_FORCE_CONTIGUOUS))
1011                 return iommu_dma_alloc_remap(dev, size, handle, gfp, attrs);
1012
1013         if (IS_ENABLED(CONFIG_DMA_DIRECT_REMAP) &&
1014             !gfpflags_allow_blocking(gfp) && !coherent)
1015                 cpu_addr = dma_alloc_from_pool(PAGE_ALIGN(size), &page, gfp);
1016         else
1017                 cpu_addr = iommu_dma_alloc_pages(dev, size, &page, gfp, attrs);
1018         if (!cpu_addr)
1019                 return NULL;
1020
1021         *handle = __iommu_dma_map(dev, page_to_phys(page), size, ioprot);
1022         if (*handle == DMA_MAPPING_ERROR) {
1023                 __iommu_dma_free(dev, size, cpu_addr);
1024                 return NULL;
1025         }
1026
1027         return cpu_addr;
1028 }
1029
1030 static int iommu_dma_mmap(struct device *dev, struct vm_area_struct *vma,
1031                 void *cpu_addr, dma_addr_t dma_addr, size_t size,
1032                 unsigned long attrs)
1033 {
1034         unsigned long nr_pages = PAGE_ALIGN(size) >> PAGE_SHIFT;
1035         unsigned long pfn, off = vma->vm_pgoff;
1036         int ret;
1037
1038         vma->vm_page_prot = dma_pgprot(dev, vma->vm_page_prot, attrs);
1039
1040         if (dma_mmap_from_dev_coherent(dev, vma, cpu_addr, size, &ret))
1041                 return ret;
1042
1043         if (off >= nr_pages || vma_pages(vma) > nr_pages - off)
1044                 return -ENXIO;
1045
1046         if (IS_ENABLED(CONFIG_DMA_REMAP) && is_vmalloc_addr(cpu_addr)) {
1047                 struct page **pages = dma_common_find_pages(cpu_addr);
1048
1049                 if (pages)
1050                         return __iommu_dma_mmap(pages, size, vma);
1051                 pfn = vmalloc_to_pfn(cpu_addr);
1052         } else {
1053                 pfn = page_to_pfn(virt_to_page(cpu_addr));
1054         }
1055
1056         return remap_pfn_range(vma, vma->vm_start, pfn + off,
1057                                vma->vm_end - vma->vm_start,
1058                                vma->vm_page_prot);
1059 }
1060
1061 static int iommu_dma_get_sgtable(struct device *dev, struct sg_table *sgt,
1062                 void *cpu_addr, dma_addr_t dma_addr, size_t size,
1063                 unsigned long attrs)
1064 {
1065         struct page *page;
1066         int ret;
1067
1068         if (IS_ENABLED(CONFIG_DMA_REMAP) && is_vmalloc_addr(cpu_addr)) {
1069                 struct page **pages = dma_common_find_pages(cpu_addr);
1070
1071                 if (pages) {
1072                         return sg_alloc_table_from_pages(sgt, pages,
1073                                         PAGE_ALIGN(size) >> PAGE_SHIFT,
1074                                         0, size, GFP_KERNEL);
1075                 }
1076
1077                 page = vmalloc_to_page(cpu_addr);
1078         } else {
1079                 page = virt_to_page(cpu_addr);
1080         }
1081
1082         ret = sg_alloc_table(sgt, 1, GFP_KERNEL);
1083         if (!ret)
1084                 sg_set_page(sgt->sgl, page, PAGE_ALIGN(size), 0);
1085         return ret;
1086 }
1087
1088 static unsigned long iommu_dma_get_merge_boundary(struct device *dev)
1089 {
1090         struct iommu_domain *domain = iommu_get_dma_domain(dev);
1091
1092         return (1UL << __ffs(domain->pgsize_bitmap)) - 1;
1093 }
1094
1095 static const struct dma_map_ops iommu_dma_ops = {
1096         .alloc                  = iommu_dma_alloc,
1097         .free                   = iommu_dma_free,
1098         .mmap                   = iommu_dma_mmap,
1099         .get_sgtable            = iommu_dma_get_sgtable,
1100         .map_page               = iommu_dma_map_page,
1101         .unmap_page             = iommu_dma_unmap_page,
1102         .map_sg                 = iommu_dma_map_sg,
1103         .unmap_sg               = iommu_dma_unmap_sg,
1104         .sync_single_for_cpu    = iommu_dma_sync_single_for_cpu,
1105         .sync_single_for_device = iommu_dma_sync_single_for_device,
1106         .sync_sg_for_cpu        = iommu_dma_sync_sg_for_cpu,
1107         .sync_sg_for_device     = iommu_dma_sync_sg_for_device,
1108         .map_resource           = iommu_dma_map_resource,
1109         .unmap_resource         = iommu_dma_unmap_resource,
1110         .get_merge_boundary     = iommu_dma_get_merge_boundary,
1111 };
1112
1113 /*
1114  * The IOMMU core code allocates the default DMA domain, which the underlying
1115  * IOMMU driver needs to support via the dma-iommu layer.
1116  */
1117 void iommu_setup_dma_ops(struct device *dev, u64 dma_base, u64 size)
1118 {
1119         struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
1120
1121         if (!domain)
1122                 goto out_err;
1123
1124         /*
1125          * The IOMMU core code allocates the default DMA domain, which the
1126          * underlying IOMMU driver needs to support via the dma-iommu layer.
1127          */
1128         if (domain->type == IOMMU_DOMAIN_DMA) {
1129                 if (iommu_dma_init_domain(domain, dma_base, size, dev))
1130                         goto out_err;
1131                 dev->dma_ops = &iommu_dma_ops;
1132         }
1133
1134         return;
1135 out_err:
1136          pr_warn("Failed to set up IOMMU for device %s; retaining platform DMA ops\n",
1137                  dev_name(dev));
1138 }
1139
1140 static struct iommu_dma_msi_page *iommu_dma_get_msi_page(struct device *dev,
1141                 phys_addr_t msi_addr, struct iommu_domain *domain)
1142 {
1143         struct iommu_dma_cookie *cookie = domain->iova_cookie;
1144         struct iommu_dma_msi_page *msi_page;
1145         dma_addr_t iova;
1146         int prot = IOMMU_WRITE | IOMMU_NOEXEC | IOMMU_MMIO;
1147         size_t size = cookie_msi_granule(cookie);
1148
1149         msi_addr &= ~(phys_addr_t)(size - 1);
1150         list_for_each_entry(msi_page, &cookie->msi_page_list, list)
1151                 if (msi_page->phys == msi_addr)
1152                         return msi_page;
1153
1154         msi_page = kzalloc(sizeof(*msi_page), GFP_KERNEL);
1155         if (!msi_page)
1156                 return NULL;
1157
1158         iova = iommu_dma_alloc_iova(domain, size, dma_get_mask(dev), dev);
1159         if (!iova)
1160                 goto out_free_page;
1161
1162         if (iommu_map(domain, iova, msi_addr, size, prot))
1163                 goto out_free_iova;
1164
1165         INIT_LIST_HEAD(&msi_page->list);
1166         msi_page->phys = msi_addr;
1167         msi_page->iova = iova;
1168         list_add(&msi_page->list, &cookie->msi_page_list);
1169         return msi_page;
1170
1171 out_free_iova:
1172         iommu_dma_free_iova(cookie, iova, size);
1173 out_free_page:
1174         kfree(msi_page);
1175         return NULL;
1176 }
1177
1178 int iommu_dma_prepare_msi(struct msi_desc *desc, phys_addr_t msi_addr)
1179 {
1180         struct device *dev = msi_desc_to_dev(desc);
1181         struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
1182         struct iommu_dma_msi_page *msi_page;
1183         static DEFINE_MUTEX(msi_prepare_lock); /* see below */
1184
1185         if (!domain || !domain->iova_cookie) {
1186                 desc->iommu_cookie = NULL;
1187                 return 0;
1188         }
1189
1190         /*
1191          * In fact the whole prepare operation should already be serialised by
1192          * irq_domain_mutex further up the callchain, but that's pretty subtle
1193          * on its own, so consider this locking as failsafe documentation...
1194          */
1195         mutex_lock(&msi_prepare_lock);
1196         msi_page = iommu_dma_get_msi_page(dev, msi_addr, domain);
1197         mutex_unlock(&msi_prepare_lock);
1198
1199         msi_desc_set_iommu_cookie(desc, msi_page);
1200
1201         if (!msi_page)
1202                 return -ENOMEM;
1203         return 0;
1204 }
1205
1206 void iommu_dma_compose_msi_msg(struct msi_desc *desc,
1207                                struct msi_msg *msg)
1208 {
1209         struct device *dev = msi_desc_to_dev(desc);
1210         const struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
1211         const struct iommu_dma_msi_page *msi_page;
1212
1213         msi_page = msi_desc_get_iommu_cookie(desc);
1214
1215         if (!domain || !domain->iova_cookie || WARN_ON(!msi_page))
1216                 return;
1217
1218         msg->address_hi = upper_32_bits(msi_page->iova);
1219         msg->address_lo &= cookie_msi_granule(domain->iova_cookie) - 1;
1220         msg->address_lo += lower_32_bits(msi_page->iova);
1221 }
1222
1223 static int iommu_dma_init(void)
1224 {
1225         return iova_cache_get();
1226 }
1227 arch_initcall(iommu_dma_init);