dma-iommu.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. /*
  2. * A fairly generic DMA-API to IOMMU-API glue layer.
  3. *
  4. * Copyright (C) 2014-2015 ARM Ltd.
  5. *
  6. * based in part on arch/arm/mm/dma-mapping.c:
  7. * Copyright (C) 2000-2004 Russell King
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2 as
  11. * published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. #include <linux/device.h>
  22. #include <linux/dma-iommu.h>
  23. #include <linux/gfp.h>
  24. #include <linux/huge_mm.h>
  25. #include <linux/iommu.h>
  26. #include <linux/iova.h>
  27. #include <linux/mm.h>
  28. #include <linux/scatterlist.h>
  29. #include <linux/vmalloc.h>
  30. int iommu_dma_init(void)
  31. {
  32. return iova_cache_get();
  33. }
  34. /**
  35. * iommu_get_dma_cookie - Acquire DMA-API resources for a domain
  36. * @domain: IOMMU domain to prepare for DMA-API usage
  37. *
  38. * IOMMU drivers should normally call this from their domain_alloc
  39. * callback when domain->type == IOMMU_DOMAIN_DMA.
  40. */
  41. int iommu_get_dma_cookie(struct iommu_domain *domain)
  42. {
  43. struct iova_domain *iovad;
  44. if (domain->iova_cookie)
  45. return -EEXIST;
  46. iovad = kzalloc(sizeof(*iovad), GFP_KERNEL);
  47. domain->iova_cookie = iovad;
  48. return iovad ? 0 : -ENOMEM;
  49. }
  50. EXPORT_SYMBOL(iommu_get_dma_cookie);
  51. /**
  52. * iommu_put_dma_cookie - Release a domain's DMA mapping resources
  53. * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie()
  54. *
  55. * IOMMU drivers should normally call this from their domain_free callback.
  56. */
  57. void iommu_put_dma_cookie(struct iommu_domain *domain)
  58. {
  59. struct iova_domain *iovad = domain->iova_cookie;
  60. if (!iovad)
  61. return;
  62. put_iova_domain(iovad);
  63. kfree(iovad);
  64. domain->iova_cookie = NULL;
  65. }
  66. EXPORT_SYMBOL(iommu_put_dma_cookie);
  67. /**
  68. * iommu_dma_init_domain - Initialise a DMA mapping domain
  69. * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie()
  70. * @base: IOVA at which the mappable address space starts
  71. * @size: Size of IOVA space
  72. *
  73. * @base and @size should be exact multiples of IOMMU page granularity to
  74. * avoid rounding surprises. If necessary, we reserve the page at address 0
  75. * to ensure it is an invalid IOVA. It is safe to reinitialise a domain, but
  76. * any change which could make prior IOVAs invalid will fail.
  77. */
  78. int iommu_dma_init_domain(struct iommu_domain *domain, dma_addr_t base, u64 size)
  79. {
  80. struct iova_domain *iovad = domain->iova_cookie;
  81. unsigned long order, base_pfn, end_pfn;
  82. if (!iovad)
  83. return -ENODEV;
  84. /* Use the smallest supported page size for IOVA granularity */
  85. order = __ffs(domain->pgsize_bitmap);
  86. base_pfn = max_t(unsigned long, 1, base >> order);
  87. end_pfn = (base + size - 1) >> order;
  88. /* Check the domain allows at least some access to the device... */
  89. if (domain->geometry.force_aperture) {
  90. if (base > domain->geometry.aperture_end ||
  91. base + size <= domain->geometry.aperture_start) {
  92. pr_warn("specified DMA range outside IOMMU capability\n");
  93. return -EFAULT;
  94. }
  95. /* ...then finally give it a kicking to make sure it fits */
  96. base_pfn = max_t(unsigned long, base_pfn,
  97. domain->geometry.aperture_start >> order);
  98. end_pfn = min_t(unsigned long, end_pfn,
  99. domain->geometry.aperture_end >> order);
  100. }
  101. /* All we can safely do with an existing domain is enlarge it */
  102. if (iovad->start_pfn) {
  103. if (1UL << order != iovad->granule ||
  104. base_pfn != iovad->start_pfn ||
  105. end_pfn < iovad->dma_32bit_pfn) {
  106. pr_warn("Incompatible range for DMA domain\n");
  107. return -EFAULT;
  108. }
  109. iovad->dma_32bit_pfn = end_pfn;
  110. } else {
  111. init_iova_domain(iovad, 1UL << order, base_pfn, end_pfn);
  112. }
  113. return 0;
  114. }
  115. EXPORT_SYMBOL(iommu_dma_init_domain);
  116. /**
  117. * dma_direction_to_prot - Translate DMA API directions to IOMMU API page flags
  118. * @dir: Direction of DMA transfer
  119. * @coherent: Is the DMA master cache-coherent?
  120. *
  121. * Return: corresponding IOMMU API page protection flags
  122. */
  123. int dma_direction_to_prot(enum dma_data_direction dir, bool coherent)
  124. {
  125. int prot = coherent ? IOMMU_CACHE : 0;
  126. switch (dir) {
  127. case DMA_BIDIRECTIONAL:
  128. return prot | IOMMU_READ | IOMMU_WRITE;
  129. case DMA_TO_DEVICE:
  130. return prot | IOMMU_READ;
  131. case DMA_FROM_DEVICE:
  132. return prot | IOMMU_WRITE;
  133. default:
  134. return 0;
  135. }
  136. }
  137. static struct iova *__alloc_iova(struct iova_domain *iovad, size_t size,
  138. dma_addr_t dma_limit)
  139. {
  140. unsigned long shift = iova_shift(iovad);
  141. unsigned long length = iova_align(iovad, size) >> shift;
  142. /*
  143. * Enforce size-alignment to be safe - there could perhaps be an
  144. * attribute to control this per-device, or at least per-domain...
  145. */
  146. return alloc_iova(iovad, length, dma_limit >> shift, true);
  147. }
  148. /* The IOVA allocator knows what we mapped, so just unmap whatever that was */
  149. static void __iommu_dma_unmap(struct iommu_domain *domain, dma_addr_t dma_addr)
  150. {
  151. struct iova_domain *iovad = domain->iova_cookie;
  152. unsigned long shift = iova_shift(iovad);
  153. unsigned long pfn = dma_addr >> shift;
  154. struct iova *iova = find_iova(iovad, pfn);
  155. size_t size;
  156. if (WARN_ON(!iova))
  157. return;
  158. size = iova_size(iova) << shift;
  159. size -= iommu_unmap(domain, pfn << shift, size);
  160. /* ...and if we can't, then something is horribly, horribly wrong */
  161. WARN_ON(size > 0);
  162. __free_iova(iovad, iova);
  163. }
  164. static void __iommu_dma_free_pages(struct page **pages, int count)
  165. {
  166. while (count--)
  167. __free_page(pages[count]);
  168. kvfree(pages);
  169. }
  170. static struct page **__iommu_dma_alloc_pages(unsigned int count,
  171. unsigned long order_mask, gfp_t gfp)
  172. {
  173. struct page **pages;
  174. unsigned int i = 0, array_size = count * sizeof(*pages);
  175. order_mask &= (2U << MAX_ORDER) - 1;
  176. if (!order_mask)
  177. return NULL;
  178. if (array_size <= PAGE_SIZE)
  179. pages = kzalloc(array_size, GFP_KERNEL);
  180. else
  181. pages = vzalloc(array_size);
  182. if (!pages)
  183. return NULL;
  184. /* IOMMU can map any pages, so himem can also be used here */
  185. gfp |= __GFP_NOWARN | __GFP_HIGHMEM;
  186. while (count) {
  187. struct page *page = NULL;
  188. unsigned int order_size;
  189. /*
  190. * Higher-order allocations are a convenience rather
  191. * than a necessity, hence using __GFP_NORETRY until
  192. * falling back to minimum-order allocations.
  193. */
  194. for (order_mask &= (2U << __fls(count)) - 1;
  195. order_mask; order_mask &= ~order_size) {
  196. unsigned int order = __fls(order_mask);
  197. order_size = 1U << order;
  198. page = alloc_pages((order_mask - order_size) ?
  199. gfp | __GFP_NORETRY : gfp, order);
  200. if (!page)
  201. continue;
  202. if (!order)
  203. break;
  204. if (!PageCompound(page)) {
  205. split_page(page, order);
  206. break;
  207. } else if (!split_huge_page(page)) {
  208. break;
  209. }
  210. __free_pages(page, order);
  211. }
  212. if (!page) {
  213. __iommu_dma_free_pages(pages, i);
  214. return NULL;
  215. }
  216. count -= order_size;
  217. while (order_size--)
  218. pages[i++] = page++;
  219. }
  220. return pages;
  221. }
  222. /**
  223. * iommu_dma_free - Free a buffer allocated by iommu_dma_alloc()
  224. * @dev: Device which owns this buffer
  225. * @pages: Array of buffer pages as returned by iommu_dma_alloc()
  226. * @size: Size of buffer in bytes
  227. * @handle: DMA address of buffer
  228. *
  229. * Frees both the pages associated with the buffer, and the array
  230. * describing them
  231. */
  232. void iommu_dma_free(struct device *dev, struct page **pages, size_t size,
  233. dma_addr_t *handle)
  234. {
  235. __iommu_dma_unmap(iommu_get_domain_for_dev(dev), *handle);
  236. __iommu_dma_free_pages(pages, PAGE_ALIGN(size) >> PAGE_SHIFT);
  237. *handle = DMA_ERROR_CODE;
  238. }
  239. /**
  240. * iommu_dma_alloc - Allocate and map a buffer contiguous in IOVA space
  241. * @dev: Device to allocate memory for. Must be a real device
  242. * attached to an iommu_dma_domain
  243. * @size: Size of buffer in bytes
  244. * @gfp: Allocation flags
  245. * @attrs: DMA attributes for this allocation
  246. * @prot: IOMMU mapping flags
  247. * @handle: Out argument for allocated DMA handle
  248. * @flush_page: Arch callback which must ensure PAGE_SIZE bytes from the
  249. * given VA/PA are visible to the given non-coherent device.
  250. *
  251. * If @size is less than PAGE_SIZE, then a full CPU page will be allocated,
  252. * but an IOMMU which supports smaller pages might not map the whole thing.
  253. *
  254. * Return: Array of struct page pointers describing the buffer,
  255. * or NULL on failure.
  256. */
  257. struct page **iommu_dma_alloc(struct device *dev, size_t size, gfp_t gfp,
  258. unsigned long attrs, int prot, dma_addr_t *handle,
  259. void (*flush_page)(struct device *, const void *, phys_addr_t))
  260. {
  261. struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
  262. struct iova_domain *iovad = domain->iova_cookie;
  263. struct iova *iova;
  264. struct page **pages;
  265. struct sg_table sgt;
  266. dma_addr_t dma_addr;
  267. unsigned int count, min_size, alloc_sizes = domain->pgsize_bitmap;
  268. *handle = DMA_ERROR_CODE;
  269. min_size = alloc_sizes & -alloc_sizes;
  270. if (min_size < PAGE_SIZE) {
  271. min_size = PAGE_SIZE;
  272. alloc_sizes |= PAGE_SIZE;
  273. } else {
  274. size = ALIGN(size, min_size);
  275. }
  276. if (attrs & DMA_ATTR_ALLOC_SINGLE_PAGES)
  277. alloc_sizes = min_size;
  278. count = PAGE_ALIGN(size) >> PAGE_SHIFT;
  279. pages = __iommu_dma_alloc_pages(count, alloc_sizes >> PAGE_SHIFT, gfp);
  280. if (!pages)
  281. return NULL;
  282. iova = __alloc_iova(iovad, size, dev->coherent_dma_mask);
  283. if (!iova)
  284. goto out_free_pages;
  285. size = iova_align(iovad, size);
  286. if (sg_alloc_table_from_pages(&sgt, pages, count, 0, size, GFP_KERNEL))
  287. goto out_free_iova;
  288. if (!(prot & IOMMU_CACHE)) {
  289. struct sg_mapping_iter miter;
  290. /*
  291. * The CPU-centric flushing implied by SG_MITER_TO_SG isn't
  292. * sufficient here, so skip it by using the "wrong" direction.
  293. */
  294. sg_miter_start(&miter, sgt.sgl, sgt.orig_nents, SG_MITER_FROM_SG);
  295. while (sg_miter_next(&miter))
  296. flush_page(dev, miter.addr, page_to_phys(miter.page));
  297. sg_miter_stop(&miter);
  298. }
  299. dma_addr = iova_dma_addr(iovad, iova);
  300. if (iommu_map_sg(domain, dma_addr, sgt.sgl, sgt.orig_nents, prot)
  301. < size)
  302. goto out_free_sg;
  303. *handle = dma_addr;
  304. sg_free_table(&sgt);
  305. return pages;
  306. out_free_sg:
  307. sg_free_table(&sgt);
  308. out_free_iova:
  309. __free_iova(iovad, iova);
  310. out_free_pages:
  311. __iommu_dma_free_pages(pages, count);
  312. return NULL;
  313. }
  314. /**
  315. * iommu_dma_mmap - Map a buffer into provided user VMA
  316. * @pages: Array representing buffer from iommu_dma_alloc()
  317. * @size: Size of buffer in bytes
  318. * @vma: VMA describing requested userspace mapping
  319. *
  320. * Maps the pages of the buffer in @pages into @vma. The caller is responsible
  321. * for verifying the correct size and protection of @vma beforehand.
  322. */
  323. int iommu_dma_mmap(struct page **pages, size_t size, struct vm_area_struct *vma)
  324. {
  325. unsigned long uaddr = vma->vm_start;
  326. unsigned int i, count = PAGE_ALIGN(size) >> PAGE_SHIFT;
  327. int ret = -ENXIO;
  328. for (i = vma->vm_pgoff; i < count && uaddr < vma->vm_end; i++) {
  329. ret = vm_insert_page(vma, uaddr, pages[i]);
  330. if (ret)
  331. break;
  332. uaddr += PAGE_SIZE;
  333. }
  334. return ret;
  335. }
  336. dma_addr_t iommu_dma_map_page(struct device *dev, struct page *page,
  337. unsigned long offset, size_t size, int prot)
  338. {
  339. dma_addr_t dma_addr;
  340. struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
  341. struct iova_domain *iovad = domain->iova_cookie;
  342. phys_addr_t phys = page_to_phys(page) + offset;
  343. size_t iova_off = iova_offset(iovad, phys);
  344. size_t len = iova_align(iovad, size + iova_off);
  345. struct iova *iova = __alloc_iova(iovad, len, dma_get_mask(dev));
  346. if (!iova)
  347. return DMA_ERROR_CODE;
  348. dma_addr = iova_dma_addr(iovad, iova);
  349. if (iommu_map(domain, dma_addr, phys - iova_off, len, prot)) {
  350. __free_iova(iovad, iova);
  351. return DMA_ERROR_CODE;
  352. }
  353. return dma_addr + iova_off;
  354. }
  355. void iommu_dma_unmap_page(struct device *dev, dma_addr_t handle, size_t size,
  356. enum dma_data_direction dir, unsigned long attrs)
  357. {
  358. __iommu_dma_unmap(iommu_get_domain_for_dev(dev), handle);
  359. }
  360. /*
  361. * Prepare a successfully-mapped scatterlist to give back to the caller.
  362. *
  363. * At this point the segments are already laid out by iommu_dma_map_sg() to
  364. * avoid individually crossing any boundaries, so we merely need to check a
  365. * segment's start address to avoid concatenating across one.
  366. */
  367. static int __finalise_sg(struct device *dev, struct scatterlist *sg, int nents,
  368. dma_addr_t dma_addr)
  369. {
  370. struct scatterlist *s, *cur = sg;
  371. unsigned long seg_mask = dma_get_seg_boundary(dev);
  372. unsigned int cur_len = 0, max_len = dma_get_max_seg_size(dev);
  373. int i, count = 0;
  374. for_each_sg(sg, s, nents, i) {
  375. /* Restore this segment's original unaligned fields first */
  376. unsigned int s_iova_off = sg_dma_address(s);
  377. unsigned int s_length = sg_dma_len(s);
  378. unsigned int s_iova_len = s->length;
  379. s->offset += s_iova_off;
  380. s->length = s_length;
  381. sg_dma_address(s) = DMA_ERROR_CODE;
  382. sg_dma_len(s) = 0;
  383. /*
  384. * Now fill in the real DMA data. If...
  385. * - there is a valid output segment to append to
  386. * - and this segment starts on an IOVA page boundary
  387. * - but doesn't fall at a segment boundary
  388. * - and wouldn't make the resulting output segment too long
  389. */
  390. if (cur_len && !s_iova_off && (dma_addr & seg_mask) &&
  391. (cur_len + s_length <= max_len)) {
  392. /* ...then concatenate it with the previous one */
  393. cur_len += s_length;
  394. } else {
  395. /* Otherwise start the next output segment */
  396. if (i > 0)
  397. cur = sg_next(cur);
  398. cur_len = s_length;
  399. count++;
  400. sg_dma_address(cur) = dma_addr + s_iova_off;
  401. }
  402. sg_dma_len(cur) = cur_len;
  403. dma_addr += s_iova_len;
  404. if (s_length + s_iova_off < s_iova_len)
  405. cur_len = 0;
  406. }
  407. return count;
  408. }
  409. /*
  410. * If mapping failed, then just restore the original list,
  411. * but making sure the DMA fields are invalidated.
  412. */
  413. static void __invalidate_sg(struct scatterlist *sg, int nents)
  414. {
  415. struct scatterlist *s;
  416. int i;
  417. for_each_sg(sg, s, nents, i) {
  418. if (sg_dma_address(s) != DMA_ERROR_CODE)
  419. s->offset += sg_dma_address(s);
  420. if (sg_dma_len(s))
  421. s->length = sg_dma_len(s);
  422. sg_dma_address(s) = DMA_ERROR_CODE;
  423. sg_dma_len(s) = 0;
  424. }
  425. }
  426. /*
  427. * The DMA API client is passing in a scatterlist which could describe
  428. * any old buffer layout, but the IOMMU API requires everything to be
  429. * aligned to IOMMU pages. Hence the need for this complicated bit of
  430. * impedance-matching, to be able to hand off a suitably-aligned list,
  431. * but still preserve the original offsets and sizes for the caller.
  432. */
  433. int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg,
  434. int nents, int prot)
  435. {
  436. struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
  437. struct iova_domain *iovad = domain->iova_cookie;
  438. struct iova *iova;
  439. struct scatterlist *s, *prev = NULL;
  440. dma_addr_t dma_addr;
  441. size_t iova_len = 0;
  442. unsigned long mask = dma_get_seg_boundary(dev);
  443. int i;
  444. /*
  445. * Work out how much IOVA space we need, and align the segments to
  446. * IOVA granules for the IOMMU driver to handle. With some clever
  447. * trickery we can modify the list in-place, but reversibly, by
  448. * stashing the unaligned parts in the as-yet-unused DMA fields.
  449. */
  450. for_each_sg(sg, s, nents, i) {
  451. size_t s_iova_off = iova_offset(iovad, s->offset);
  452. size_t s_length = s->length;
  453. size_t pad_len = (mask - iova_len + 1) & mask;
  454. sg_dma_address(s) = s_iova_off;
  455. sg_dma_len(s) = s_length;
  456. s->offset -= s_iova_off;
  457. s_length = iova_align(iovad, s_length + s_iova_off);
  458. s->length = s_length;
  459. /*
  460. * Due to the alignment of our single IOVA allocation, we can
  461. * depend on these assumptions about the segment boundary mask:
  462. * - If mask size >= IOVA size, then the IOVA range cannot
  463. * possibly fall across a boundary, so we don't care.
  464. * - If mask size < IOVA size, then the IOVA range must start
  465. * exactly on a boundary, therefore we can lay things out
  466. * based purely on segment lengths without needing to know
  467. * the actual addresses beforehand.
  468. * - The mask must be a power of 2, so pad_len == 0 if
  469. * iova_len == 0, thus we cannot dereference prev the first
  470. * time through here (i.e. before it has a meaningful value).
  471. */
  472. if (pad_len && pad_len < s_length - 1) {
  473. prev->length += pad_len;
  474. iova_len += pad_len;
  475. }
  476. iova_len += s_length;
  477. prev = s;
  478. }
  479. iova = __alloc_iova(iovad, iova_len, dma_get_mask(dev));
  480. if (!iova)
  481. goto out_restore_sg;
  482. /*
  483. * We'll leave any physical concatenation to the IOMMU driver's
  484. * implementation - it knows better than we do.
  485. */
  486. dma_addr = iova_dma_addr(iovad, iova);
  487. if (iommu_map_sg(domain, dma_addr, sg, nents, prot) < iova_len)
  488. goto out_free_iova;
  489. return __finalise_sg(dev, sg, nents, dma_addr);
  490. out_free_iova:
  491. __free_iova(iovad, iova);
  492. out_restore_sg:
  493. __invalidate_sg(sg, nents);
  494. return 0;
  495. }
  496. void iommu_dma_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
  497. enum dma_data_direction dir, unsigned long attrs)
  498. {
  499. /*
  500. * The scatterlist segments are mapped into a single
  501. * contiguous IOVA allocation, so this is incredibly easy.
  502. */
  503. __iommu_dma_unmap(iommu_get_domain_for_dev(dev), sg_dma_address(sg));
  504. }
  505. int iommu_dma_supported(struct device *dev, u64 mask)
  506. {
  507. /*
  508. * 'Special' IOMMUs which don't have the same addressing capability
  509. * as the CPU will have to wait until we have some way to query that
  510. * before they'll be able to use this framework.
  511. */
  512. return 1;
  513. }
  514. int iommu_dma_mapping_error(struct device *dev, dma_addr_t dma_addr)
  515. {
  516. return dma_addr == DMA_ERROR_CODE;
  517. }