dma-iommu.c 17 KB

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