dma-iommu.c 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864
  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. #include <linux/acpi_iort.h>
  11. #include <linux/atomic.h>
  12. #include <linux/crash_dump.h>
  13. #include <linux/device.h>
  14. #include <linux/dma-direct.h>
  15. #include <linux/dma-map-ops.h>
  16. #include <linux/gfp.h>
  17. #include <linux/huge_mm.h>
  18. #include <linux/iommu.h>
  19. #include <linux/iommu-dma.h>
  20. #include <linux/iova.h>
  21. #include <linux/irq.h>
  22. #include <linux/list_sort.h>
  23. #include <linux/memremap.h>
  24. #include <linux/mm.h>
  25. #include <linux/mutex.h>
  26. #include <linux/of_iommu.h>
  27. #include <linux/pci.h>
  28. #include <linux/scatterlist.h>
  29. #include <linux/spinlock.h>
  30. #include <linux/swiotlb.h>
  31. #include <linux/vmalloc.h>
  32. #include <trace/events/swiotlb.h>
  33. #include "dma-iommu.h"
  34. #include "iommu-pages.h"
  35. struct iommu_dma_msi_page {
  36. struct list_head list;
  37. dma_addr_t iova;
  38. phys_addr_t phys;
  39. };
  40. enum iommu_dma_cookie_type {
  41. IOMMU_DMA_IOVA_COOKIE,
  42. IOMMU_DMA_MSI_COOKIE,
  43. };
  44. enum iommu_dma_queue_type {
  45. IOMMU_DMA_OPTS_PER_CPU_QUEUE,
  46. IOMMU_DMA_OPTS_SINGLE_QUEUE,
  47. };
  48. struct iommu_dma_options {
  49. enum iommu_dma_queue_type qt;
  50. size_t fq_size;
  51. unsigned int fq_timeout;
  52. };
  53. struct iommu_dma_cookie {
  54. enum iommu_dma_cookie_type type;
  55. union {
  56. /* Full allocator for IOMMU_DMA_IOVA_COOKIE */
  57. struct {
  58. struct iova_domain iovad;
  59. /* Flush queue */
  60. union {
  61. struct iova_fq *single_fq;
  62. struct iova_fq __percpu *percpu_fq;
  63. };
  64. /* Number of TLB flushes that have been started */
  65. atomic64_t fq_flush_start_cnt;
  66. /* Number of TLB flushes that have been finished */
  67. atomic64_t fq_flush_finish_cnt;
  68. /* Timer to regularily empty the flush queues */
  69. struct timer_list fq_timer;
  70. /* 1 when timer is active, 0 when not */
  71. atomic_t fq_timer_on;
  72. };
  73. /* Trivial linear page allocator for IOMMU_DMA_MSI_COOKIE */
  74. dma_addr_t msi_iova;
  75. };
  76. struct list_head msi_page_list;
  77. /* Domain for flush queue callback; NULL if flush queue not in use */
  78. struct iommu_domain *fq_domain;
  79. /* Options for dma-iommu use */
  80. struct iommu_dma_options options;
  81. struct mutex mutex;
  82. };
  83. static DEFINE_STATIC_KEY_FALSE(iommu_deferred_attach_enabled);
  84. bool iommu_dma_forcedac __read_mostly;
  85. static int __init iommu_dma_forcedac_setup(char *str)
  86. {
  87. int ret = kstrtobool(str, &iommu_dma_forcedac);
  88. if (!ret && iommu_dma_forcedac)
  89. pr_info("Forcing DAC for PCI devices\n");
  90. return ret;
  91. }
  92. early_param("iommu.forcedac", iommu_dma_forcedac_setup);
  93. /* Number of entries per flush queue */
  94. #define IOVA_DEFAULT_FQ_SIZE 256
  95. #define IOVA_SINGLE_FQ_SIZE 32768
  96. /* Timeout (in ms) after which entries are flushed from the queue */
  97. #define IOVA_DEFAULT_FQ_TIMEOUT 10
  98. #define IOVA_SINGLE_FQ_TIMEOUT 1000
  99. /* Flush queue entry for deferred flushing */
  100. struct iova_fq_entry {
  101. unsigned long iova_pfn;
  102. unsigned long pages;
  103. struct list_head freelist;
  104. u64 counter; /* Flush counter when this entry was added */
  105. };
  106. /* Per-CPU flush queue structure */
  107. struct iova_fq {
  108. spinlock_t lock;
  109. unsigned int head, tail;
  110. unsigned int mod_mask;
  111. struct iova_fq_entry entries[];
  112. };
  113. #define fq_ring_for_each(i, fq) \
  114. for ((i) = (fq)->head; (i) != (fq)->tail; (i) = ((i) + 1) & (fq)->mod_mask)
  115. static inline bool fq_full(struct iova_fq *fq)
  116. {
  117. assert_spin_locked(&fq->lock);
  118. return (((fq->tail + 1) & fq->mod_mask) == fq->head);
  119. }
  120. static inline unsigned int fq_ring_add(struct iova_fq *fq)
  121. {
  122. unsigned int idx = fq->tail;
  123. assert_spin_locked(&fq->lock);
  124. fq->tail = (idx + 1) & fq->mod_mask;
  125. return idx;
  126. }
  127. static void fq_ring_free_locked(struct iommu_dma_cookie *cookie, struct iova_fq *fq)
  128. {
  129. u64 counter = atomic64_read(&cookie->fq_flush_finish_cnt);
  130. unsigned int idx;
  131. assert_spin_locked(&fq->lock);
  132. fq_ring_for_each(idx, fq) {
  133. if (fq->entries[idx].counter >= counter)
  134. break;
  135. iommu_put_pages_list(&fq->entries[idx].freelist);
  136. free_iova_fast(&cookie->iovad,
  137. fq->entries[idx].iova_pfn,
  138. fq->entries[idx].pages);
  139. fq->head = (fq->head + 1) & fq->mod_mask;
  140. }
  141. }
  142. static void fq_ring_free(struct iommu_dma_cookie *cookie, struct iova_fq *fq)
  143. {
  144. unsigned long flags;
  145. spin_lock_irqsave(&fq->lock, flags);
  146. fq_ring_free_locked(cookie, fq);
  147. spin_unlock_irqrestore(&fq->lock, flags);
  148. }
  149. static void fq_flush_iotlb(struct iommu_dma_cookie *cookie)
  150. {
  151. atomic64_inc(&cookie->fq_flush_start_cnt);
  152. cookie->fq_domain->ops->flush_iotlb_all(cookie->fq_domain);
  153. atomic64_inc(&cookie->fq_flush_finish_cnt);
  154. }
  155. static void fq_flush_timeout(struct timer_list *t)
  156. {
  157. struct iommu_dma_cookie *cookie = from_timer(cookie, t, fq_timer);
  158. int cpu;
  159. atomic_set(&cookie->fq_timer_on, 0);
  160. fq_flush_iotlb(cookie);
  161. if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE) {
  162. fq_ring_free(cookie, cookie->single_fq);
  163. } else {
  164. for_each_possible_cpu(cpu)
  165. fq_ring_free(cookie, per_cpu_ptr(cookie->percpu_fq, cpu));
  166. }
  167. }
  168. static void queue_iova(struct iommu_dma_cookie *cookie,
  169. unsigned long pfn, unsigned long pages,
  170. struct list_head *freelist)
  171. {
  172. struct iova_fq *fq;
  173. unsigned long flags;
  174. unsigned int idx;
  175. /*
  176. * Order against the IOMMU driver's pagetable update from unmapping
  177. * @pte, to guarantee that fq_flush_iotlb() observes that if called
  178. * from a different CPU before we release the lock below. Full barrier
  179. * so it also pairs with iommu_dma_init_fq() to avoid seeing partially
  180. * written fq state here.
  181. */
  182. smp_mb();
  183. if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE)
  184. fq = cookie->single_fq;
  185. else
  186. fq = raw_cpu_ptr(cookie->percpu_fq);
  187. spin_lock_irqsave(&fq->lock, flags);
  188. /*
  189. * First remove all entries from the flush queue that have already been
  190. * flushed out on another CPU. This makes the fq_full() check below less
  191. * likely to be true.
  192. */
  193. fq_ring_free_locked(cookie, fq);
  194. if (fq_full(fq)) {
  195. fq_flush_iotlb(cookie);
  196. fq_ring_free_locked(cookie, fq);
  197. }
  198. idx = fq_ring_add(fq);
  199. fq->entries[idx].iova_pfn = pfn;
  200. fq->entries[idx].pages = pages;
  201. fq->entries[idx].counter = atomic64_read(&cookie->fq_flush_start_cnt);
  202. list_splice(freelist, &fq->entries[idx].freelist);
  203. spin_unlock_irqrestore(&fq->lock, flags);
  204. /* Avoid false sharing as much as possible. */
  205. if (!atomic_read(&cookie->fq_timer_on) &&
  206. !atomic_xchg(&cookie->fq_timer_on, 1))
  207. mod_timer(&cookie->fq_timer,
  208. jiffies + msecs_to_jiffies(cookie->options.fq_timeout));
  209. }
  210. static void iommu_dma_free_fq_single(struct iova_fq *fq)
  211. {
  212. int idx;
  213. fq_ring_for_each(idx, fq)
  214. iommu_put_pages_list(&fq->entries[idx].freelist);
  215. vfree(fq);
  216. }
  217. static void iommu_dma_free_fq_percpu(struct iova_fq __percpu *percpu_fq)
  218. {
  219. int cpu, idx;
  220. /* The IOVAs will be torn down separately, so just free our queued pages */
  221. for_each_possible_cpu(cpu) {
  222. struct iova_fq *fq = per_cpu_ptr(percpu_fq, cpu);
  223. fq_ring_for_each(idx, fq)
  224. iommu_put_pages_list(&fq->entries[idx].freelist);
  225. }
  226. free_percpu(percpu_fq);
  227. }
  228. static void iommu_dma_free_fq(struct iommu_dma_cookie *cookie)
  229. {
  230. if (!cookie->fq_domain)
  231. return;
  232. del_timer_sync(&cookie->fq_timer);
  233. if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE)
  234. iommu_dma_free_fq_single(cookie->single_fq);
  235. else
  236. iommu_dma_free_fq_percpu(cookie->percpu_fq);
  237. }
  238. static void iommu_dma_init_one_fq(struct iova_fq *fq, size_t fq_size)
  239. {
  240. int i;
  241. fq->head = 0;
  242. fq->tail = 0;
  243. fq->mod_mask = fq_size - 1;
  244. spin_lock_init(&fq->lock);
  245. for (i = 0; i < fq_size; i++)
  246. INIT_LIST_HEAD(&fq->entries[i].freelist);
  247. }
  248. static int iommu_dma_init_fq_single(struct iommu_dma_cookie *cookie)
  249. {
  250. size_t fq_size = cookie->options.fq_size;
  251. struct iova_fq *queue;
  252. queue = vmalloc(struct_size(queue, entries, fq_size));
  253. if (!queue)
  254. return -ENOMEM;
  255. iommu_dma_init_one_fq(queue, fq_size);
  256. cookie->single_fq = queue;
  257. return 0;
  258. }
  259. static int iommu_dma_init_fq_percpu(struct iommu_dma_cookie *cookie)
  260. {
  261. size_t fq_size = cookie->options.fq_size;
  262. struct iova_fq __percpu *queue;
  263. int cpu;
  264. queue = __alloc_percpu(struct_size(queue, entries, fq_size),
  265. __alignof__(*queue));
  266. if (!queue)
  267. return -ENOMEM;
  268. for_each_possible_cpu(cpu)
  269. iommu_dma_init_one_fq(per_cpu_ptr(queue, cpu), fq_size);
  270. cookie->percpu_fq = queue;
  271. return 0;
  272. }
  273. /* sysfs updates are serialised by the mutex of the group owning @domain */
  274. int iommu_dma_init_fq(struct iommu_domain *domain)
  275. {
  276. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  277. int rc;
  278. if (cookie->fq_domain)
  279. return 0;
  280. atomic64_set(&cookie->fq_flush_start_cnt, 0);
  281. atomic64_set(&cookie->fq_flush_finish_cnt, 0);
  282. if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE)
  283. rc = iommu_dma_init_fq_single(cookie);
  284. else
  285. rc = iommu_dma_init_fq_percpu(cookie);
  286. if (rc) {
  287. pr_warn("iova flush queue initialization failed\n");
  288. return -ENOMEM;
  289. }
  290. timer_setup(&cookie->fq_timer, fq_flush_timeout, 0);
  291. atomic_set(&cookie->fq_timer_on, 0);
  292. /*
  293. * Prevent incomplete fq state being observable. Pairs with path from
  294. * __iommu_dma_unmap() through iommu_dma_free_iova() to queue_iova()
  295. */
  296. smp_wmb();
  297. WRITE_ONCE(cookie->fq_domain, domain);
  298. return 0;
  299. }
  300. static inline size_t cookie_msi_granule(struct iommu_dma_cookie *cookie)
  301. {
  302. if (cookie->type == IOMMU_DMA_IOVA_COOKIE)
  303. return cookie->iovad.granule;
  304. return PAGE_SIZE;
  305. }
  306. static struct iommu_dma_cookie *cookie_alloc(enum iommu_dma_cookie_type type)
  307. {
  308. struct iommu_dma_cookie *cookie;
  309. cookie = kzalloc(sizeof(*cookie), GFP_KERNEL);
  310. if (cookie) {
  311. INIT_LIST_HEAD(&cookie->msi_page_list);
  312. cookie->type = type;
  313. }
  314. return cookie;
  315. }
  316. /**
  317. * iommu_get_dma_cookie - Acquire DMA-API resources for a domain
  318. * @domain: IOMMU domain to prepare for DMA-API usage
  319. */
  320. int iommu_get_dma_cookie(struct iommu_domain *domain)
  321. {
  322. if (domain->iova_cookie)
  323. return -EEXIST;
  324. domain->iova_cookie = cookie_alloc(IOMMU_DMA_IOVA_COOKIE);
  325. if (!domain->iova_cookie)
  326. return -ENOMEM;
  327. mutex_init(&domain->iova_cookie->mutex);
  328. return 0;
  329. }
  330. /**
  331. * iommu_get_msi_cookie - Acquire just MSI remapping resources
  332. * @domain: IOMMU domain to prepare
  333. * @base: Start address of IOVA region for MSI mappings
  334. *
  335. * Users who manage their own IOVA allocation and do not want DMA API support,
  336. * but would still like to take advantage of automatic MSI remapping, can use
  337. * this to initialise their own domain appropriately. Users should reserve a
  338. * contiguous IOVA region, starting at @base, large enough to accommodate the
  339. * number of PAGE_SIZE mappings necessary to cover every MSI doorbell address
  340. * used by the devices attached to @domain.
  341. */
  342. int iommu_get_msi_cookie(struct iommu_domain *domain, dma_addr_t base)
  343. {
  344. struct iommu_dma_cookie *cookie;
  345. if (domain->type != IOMMU_DOMAIN_UNMANAGED)
  346. return -EINVAL;
  347. if (domain->iova_cookie)
  348. return -EEXIST;
  349. cookie = cookie_alloc(IOMMU_DMA_MSI_COOKIE);
  350. if (!cookie)
  351. return -ENOMEM;
  352. cookie->msi_iova = base;
  353. domain->iova_cookie = cookie;
  354. return 0;
  355. }
  356. EXPORT_SYMBOL(iommu_get_msi_cookie);
  357. /**
  358. * iommu_put_dma_cookie - Release a domain's DMA mapping resources
  359. * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie() or
  360. * iommu_get_msi_cookie()
  361. */
  362. void iommu_put_dma_cookie(struct iommu_domain *domain)
  363. {
  364. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  365. struct iommu_dma_msi_page *msi, *tmp;
  366. if (!cookie)
  367. return;
  368. if (cookie->type == IOMMU_DMA_IOVA_COOKIE && cookie->iovad.granule) {
  369. iommu_dma_free_fq(cookie);
  370. put_iova_domain(&cookie->iovad);
  371. }
  372. list_for_each_entry_safe(msi, tmp, &cookie->msi_page_list, list) {
  373. list_del(&msi->list);
  374. kfree(msi);
  375. }
  376. kfree(cookie);
  377. domain->iova_cookie = NULL;
  378. }
  379. /**
  380. * iommu_dma_get_resv_regions - Reserved region driver helper
  381. * @dev: Device from iommu_get_resv_regions()
  382. * @list: Reserved region list from iommu_get_resv_regions()
  383. *
  384. * IOMMU drivers can use this to implement their .get_resv_regions callback
  385. * for general non-IOMMU-specific reservations. Currently, this covers GICv3
  386. * ITS region reservation on ACPI based ARM platforms that may require HW MSI
  387. * reservation.
  388. */
  389. void iommu_dma_get_resv_regions(struct device *dev, struct list_head *list)
  390. {
  391. if (!is_of_node(dev_iommu_fwspec_get(dev)->iommu_fwnode))
  392. iort_iommu_get_resv_regions(dev, list);
  393. if (dev->of_node)
  394. of_iommu_get_resv_regions(dev, list);
  395. }
  396. EXPORT_SYMBOL(iommu_dma_get_resv_regions);
  397. static int cookie_init_hw_msi_region(struct iommu_dma_cookie *cookie,
  398. phys_addr_t start, phys_addr_t end)
  399. {
  400. struct iova_domain *iovad = &cookie->iovad;
  401. struct iommu_dma_msi_page *msi_page;
  402. int i, num_pages;
  403. start -= iova_offset(iovad, start);
  404. num_pages = iova_align(iovad, end - start) >> iova_shift(iovad);
  405. for (i = 0; i < num_pages; i++) {
  406. msi_page = kmalloc(sizeof(*msi_page), GFP_KERNEL);
  407. if (!msi_page)
  408. return -ENOMEM;
  409. msi_page->phys = start;
  410. msi_page->iova = start;
  411. INIT_LIST_HEAD(&msi_page->list);
  412. list_add(&msi_page->list, &cookie->msi_page_list);
  413. start += iovad->granule;
  414. }
  415. return 0;
  416. }
  417. static int iommu_dma_ranges_sort(void *priv, const struct list_head *a,
  418. const struct list_head *b)
  419. {
  420. struct resource_entry *res_a = list_entry(a, typeof(*res_a), node);
  421. struct resource_entry *res_b = list_entry(b, typeof(*res_b), node);
  422. return res_a->res->start > res_b->res->start;
  423. }
  424. static int iova_reserve_pci_windows(struct pci_dev *dev,
  425. struct iova_domain *iovad)
  426. {
  427. struct pci_host_bridge *bridge = pci_find_host_bridge(dev->bus);
  428. struct resource_entry *window;
  429. unsigned long lo, hi;
  430. phys_addr_t start = 0, end;
  431. resource_list_for_each_entry(window, &bridge->windows) {
  432. if (resource_type(window->res) != IORESOURCE_MEM)
  433. continue;
  434. lo = iova_pfn(iovad, window->res->start - window->offset);
  435. hi = iova_pfn(iovad, window->res->end - window->offset);
  436. reserve_iova(iovad, lo, hi);
  437. }
  438. /* Get reserved DMA windows from host bridge */
  439. list_sort(NULL, &bridge->dma_ranges, iommu_dma_ranges_sort);
  440. resource_list_for_each_entry(window, &bridge->dma_ranges) {
  441. end = window->res->start - window->offset;
  442. resv_iova:
  443. if (end > start) {
  444. lo = iova_pfn(iovad, start);
  445. hi = iova_pfn(iovad, end);
  446. reserve_iova(iovad, lo, hi);
  447. } else if (end < start) {
  448. /* DMA ranges should be non-overlapping */
  449. dev_err(&dev->dev,
  450. "Failed to reserve IOVA [%pa-%pa]\n",
  451. &start, &end);
  452. return -EINVAL;
  453. }
  454. start = window->res->end - window->offset + 1;
  455. /* If window is last entry */
  456. if (window->node.next == &bridge->dma_ranges &&
  457. end != ~(phys_addr_t)0) {
  458. end = ~(phys_addr_t)0;
  459. goto resv_iova;
  460. }
  461. }
  462. return 0;
  463. }
  464. static int iova_reserve_iommu_regions(struct device *dev,
  465. struct iommu_domain *domain)
  466. {
  467. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  468. struct iova_domain *iovad = &cookie->iovad;
  469. struct iommu_resv_region *region;
  470. LIST_HEAD(resv_regions);
  471. int ret = 0;
  472. if (dev_is_pci(dev)) {
  473. ret = iova_reserve_pci_windows(to_pci_dev(dev), iovad);
  474. if (ret)
  475. return ret;
  476. }
  477. iommu_get_resv_regions(dev, &resv_regions);
  478. list_for_each_entry(region, &resv_regions, list) {
  479. unsigned long lo, hi;
  480. /* We ARE the software that manages these! */
  481. if (region->type == IOMMU_RESV_SW_MSI)
  482. continue;
  483. lo = iova_pfn(iovad, region->start);
  484. hi = iova_pfn(iovad, region->start + region->length - 1);
  485. reserve_iova(iovad, lo, hi);
  486. if (region->type == IOMMU_RESV_MSI)
  487. ret = cookie_init_hw_msi_region(cookie, region->start,
  488. region->start + region->length);
  489. if (ret)
  490. break;
  491. }
  492. iommu_put_resv_regions(dev, &resv_regions);
  493. return ret;
  494. }
  495. static bool dev_is_untrusted(struct device *dev)
  496. {
  497. return dev_is_pci(dev) && to_pci_dev(dev)->untrusted;
  498. }
  499. static bool dev_use_swiotlb(struct device *dev, size_t size,
  500. enum dma_data_direction dir)
  501. {
  502. return IS_ENABLED(CONFIG_SWIOTLB) &&
  503. (dev_is_untrusted(dev) ||
  504. dma_kmalloc_needs_bounce(dev, size, dir));
  505. }
  506. static bool dev_use_sg_swiotlb(struct device *dev, struct scatterlist *sg,
  507. int nents, enum dma_data_direction dir)
  508. {
  509. struct scatterlist *s;
  510. int i;
  511. if (!IS_ENABLED(CONFIG_SWIOTLB))
  512. return false;
  513. if (dev_is_untrusted(dev))
  514. return true;
  515. /*
  516. * If kmalloc() buffers are not DMA-safe for this device and
  517. * direction, check the individual lengths in the sg list. If any
  518. * element is deemed unsafe, use the swiotlb for bouncing.
  519. */
  520. if (!dma_kmalloc_safe(dev, dir)) {
  521. for_each_sg(sg, s, nents, i)
  522. if (!dma_kmalloc_size_aligned(s->length))
  523. return true;
  524. }
  525. return false;
  526. }
  527. /**
  528. * iommu_dma_init_options - Initialize dma-iommu options
  529. * @options: The options to be initialized
  530. * @dev: Device the options are set for
  531. *
  532. * This allows tuning dma-iommu specific to device properties
  533. */
  534. static void iommu_dma_init_options(struct iommu_dma_options *options,
  535. struct device *dev)
  536. {
  537. /* Shadowing IOTLB flushes do better with a single large queue */
  538. if (dev->iommu->shadow_on_flush) {
  539. options->qt = IOMMU_DMA_OPTS_SINGLE_QUEUE;
  540. options->fq_timeout = IOVA_SINGLE_FQ_TIMEOUT;
  541. options->fq_size = IOVA_SINGLE_FQ_SIZE;
  542. } else {
  543. options->qt = IOMMU_DMA_OPTS_PER_CPU_QUEUE;
  544. options->fq_size = IOVA_DEFAULT_FQ_SIZE;
  545. options->fq_timeout = IOVA_DEFAULT_FQ_TIMEOUT;
  546. }
  547. }
  548. /**
  549. * iommu_dma_init_domain - Initialise a DMA mapping domain
  550. * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie()
  551. * @dev: Device the domain is being initialised for
  552. *
  553. * If the geometry and dma_range_map include address 0, we reserve that page
  554. * to ensure it is an invalid IOVA. It is safe to reinitialise a domain, but
  555. * any change which could make prior IOVAs invalid will fail.
  556. */
  557. static int iommu_dma_init_domain(struct iommu_domain *domain, struct device *dev)
  558. {
  559. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  560. const struct bus_dma_region *map = dev->dma_range_map;
  561. unsigned long order, base_pfn;
  562. struct iova_domain *iovad;
  563. int ret;
  564. if (!cookie || cookie->type != IOMMU_DMA_IOVA_COOKIE)
  565. return -EINVAL;
  566. iovad = &cookie->iovad;
  567. /* Use the smallest supported page size for IOVA granularity */
  568. order = __ffs(domain->pgsize_bitmap);
  569. base_pfn = 1;
  570. /* Check the domain allows at least some access to the device... */
  571. if (map) {
  572. if (dma_range_map_min(map) > domain->geometry.aperture_end ||
  573. dma_range_map_max(map) < domain->geometry.aperture_start) {
  574. pr_warn("specified DMA range outside IOMMU capability\n");
  575. return -EFAULT;
  576. }
  577. }
  578. /* ...then finally give it a kicking to make sure it fits */
  579. base_pfn = max_t(unsigned long, base_pfn,
  580. domain->geometry.aperture_start >> order);
  581. /* start_pfn is always nonzero for an already-initialised domain */
  582. mutex_lock(&cookie->mutex);
  583. if (iovad->start_pfn) {
  584. if (1UL << order != iovad->granule ||
  585. base_pfn != iovad->start_pfn) {
  586. pr_warn("Incompatible range for DMA domain\n");
  587. ret = -EFAULT;
  588. goto done_unlock;
  589. }
  590. ret = 0;
  591. goto done_unlock;
  592. }
  593. init_iova_domain(iovad, 1UL << order, base_pfn);
  594. ret = iova_domain_init_rcaches(iovad);
  595. if (ret)
  596. goto done_unlock;
  597. iommu_dma_init_options(&cookie->options, dev);
  598. /* If the FQ fails we can simply fall back to strict mode */
  599. if (domain->type == IOMMU_DOMAIN_DMA_FQ &&
  600. (!device_iommu_capable(dev, IOMMU_CAP_DEFERRED_FLUSH) || iommu_dma_init_fq(domain)))
  601. domain->type = IOMMU_DOMAIN_DMA;
  602. ret = iova_reserve_iommu_regions(dev, domain);
  603. done_unlock:
  604. mutex_unlock(&cookie->mutex);
  605. return ret;
  606. }
  607. /**
  608. * dma_info_to_prot - Translate DMA API directions and attributes to IOMMU API
  609. * page flags.
  610. * @dir: Direction of DMA transfer
  611. * @coherent: Is the DMA master cache-coherent?
  612. * @attrs: DMA attributes for the mapping
  613. *
  614. * Return: corresponding IOMMU API page protection flags
  615. */
  616. static int dma_info_to_prot(enum dma_data_direction dir, bool coherent,
  617. unsigned long attrs)
  618. {
  619. int prot = coherent ? IOMMU_CACHE : 0;
  620. if (attrs & DMA_ATTR_PRIVILEGED)
  621. prot |= IOMMU_PRIV;
  622. switch (dir) {
  623. case DMA_BIDIRECTIONAL:
  624. return prot | IOMMU_READ | IOMMU_WRITE;
  625. case DMA_TO_DEVICE:
  626. return prot | IOMMU_READ;
  627. case DMA_FROM_DEVICE:
  628. return prot | IOMMU_WRITE;
  629. default:
  630. return 0;
  631. }
  632. }
  633. static dma_addr_t iommu_dma_alloc_iova(struct iommu_domain *domain,
  634. size_t size, u64 dma_limit, struct device *dev)
  635. {
  636. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  637. struct iova_domain *iovad = &cookie->iovad;
  638. unsigned long shift, iova_len, iova;
  639. if (cookie->type == IOMMU_DMA_MSI_COOKIE) {
  640. cookie->msi_iova += size;
  641. return cookie->msi_iova - size;
  642. }
  643. shift = iova_shift(iovad);
  644. iova_len = size >> shift;
  645. dma_limit = min_not_zero(dma_limit, dev->bus_dma_limit);
  646. if (domain->geometry.force_aperture)
  647. dma_limit = min(dma_limit, (u64)domain->geometry.aperture_end);
  648. /*
  649. * Try to use all the 32-bit PCI addresses first. The original SAC vs.
  650. * DAC reasoning loses relevance with PCIe, but enough hardware and
  651. * firmware bugs are still lurking out there that it's safest not to
  652. * venture into the 64-bit space until necessary.
  653. *
  654. * If your device goes wrong after seeing the notice then likely either
  655. * its driver is not setting DMA masks accurately, the hardware has
  656. * some inherent bug in handling >32-bit addresses, or not all the
  657. * expected address bits are wired up between the device and the IOMMU.
  658. */
  659. if (dma_limit > DMA_BIT_MASK(32) && dev->iommu->pci_32bit_workaround) {
  660. iova = alloc_iova_fast(iovad, iova_len,
  661. DMA_BIT_MASK(32) >> shift, false);
  662. if (iova)
  663. goto done;
  664. dev->iommu->pci_32bit_workaround = false;
  665. dev_notice(dev, "Using %d-bit DMA addresses\n", bits_per(dma_limit));
  666. }
  667. iova = alloc_iova_fast(iovad, iova_len, dma_limit >> shift, true);
  668. done:
  669. return (dma_addr_t)iova << shift;
  670. }
  671. static void iommu_dma_free_iova(struct iommu_dma_cookie *cookie,
  672. dma_addr_t iova, size_t size, struct iommu_iotlb_gather *gather)
  673. {
  674. struct iova_domain *iovad = &cookie->iovad;
  675. /* The MSI case is only ever cleaning up its most recent allocation */
  676. if (cookie->type == IOMMU_DMA_MSI_COOKIE)
  677. cookie->msi_iova -= size;
  678. else if (gather && gather->queued)
  679. queue_iova(cookie, iova_pfn(iovad, iova),
  680. size >> iova_shift(iovad),
  681. &gather->freelist);
  682. else
  683. free_iova_fast(iovad, iova_pfn(iovad, iova),
  684. size >> iova_shift(iovad));
  685. }
  686. static void __iommu_dma_unmap(struct device *dev, dma_addr_t dma_addr,
  687. size_t size)
  688. {
  689. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  690. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  691. struct iova_domain *iovad = &cookie->iovad;
  692. size_t iova_off = iova_offset(iovad, dma_addr);
  693. struct iommu_iotlb_gather iotlb_gather;
  694. size_t unmapped;
  695. dma_addr -= iova_off;
  696. size = iova_align(iovad, size + iova_off);
  697. iommu_iotlb_gather_init(&iotlb_gather);
  698. iotlb_gather.queued = READ_ONCE(cookie->fq_domain);
  699. unmapped = iommu_unmap_fast(domain, dma_addr, size, &iotlb_gather);
  700. WARN_ON(unmapped != size);
  701. if (!iotlb_gather.queued)
  702. iommu_iotlb_sync(domain, &iotlb_gather);
  703. iommu_dma_free_iova(cookie, dma_addr, size, &iotlb_gather);
  704. }
  705. static dma_addr_t __iommu_dma_map(struct device *dev, phys_addr_t phys,
  706. size_t size, int prot, u64 dma_mask)
  707. {
  708. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  709. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  710. struct iova_domain *iovad = &cookie->iovad;
  711. size_t iova_off = iova_offset(iovad, phys);
  712. dma_addr_t iova;
  713. if (static_branch_unlikely(&iommu_deferred_attach_enabled) &&
  714. iommu_deferred_attach(dev, domain))
  715. return DMA_MAPPING_ERROR;
  716. /* If anyone ever wants this we'd need support in the IOVA allocator */
  717. if (dev_WARN_ONCE(dev, dma_get_min_align_mask(dev) > iova_mask(iovad),
  718. "Unsupported alignment constraint\n"))
  719. return DMA_MAPPING_ERROR;
  720. size = iova_align(iovad, size + iova_off);
  721. iova = iommu_dma_alloc_iova(domain, size, dma_mask, dev);
  722. if (!iova)
  723. return DMA_MAPPING_ERROR;
  724. if (iommu_map(domain, iova, phys - iova_off, size, prot, GFP_ATOMIC)) {
  725. iommu_dma_free_iova(cookie, iova, size, NULL);
  726. return DMA_MAPPING_ERROR;
  727. }
  728. return iova + iova_off;
  729. }
  730. static void __iommu_dma_free_pages(struct page **pages, int count)
  731. {
  732. while (count--)
  733. __free_page(pages[count]);
  734. kvfree(pages);
  735. }
  736. static struct page **__iommu_dma_alloc_pages(struct device *dev,
  737. unsigned int count, unsigned long order_mask, gfp_t gfp)
  738. {
  739. struct page **pages;
  740. unsigned int i = 0, nid = dev_to_node(dev);
  741. order_mask &= GENMASK(MAX_PAGE_ORDER, 0);
  742. if (!order_mask)
  743. return NULL;
  744. pages = kvcalloc(count, sizeof(*pages), GFP_KERNEL);
  745. if (!pages)
  746. return NULL;
  747. /* IOMMU can map any pages, so himem can also be used here */
  748. gfp |= __GFP_NOWARN | __GFP_HIGHMEM;
  749. while (count) {
  750. struct page *page = NULL;
  751. unsigned int order_size;
  752. /*
  753. * Higher-order allocations are a convenience rather
  754. * than a necessity, hence using __GFP_NORETRY until
  755. * falling back to minimum-order allocations.
  756. */
  757. for (order_mask &= GENMASK(__fls(count), 0);
  758. order_mask; order_mask &= ~order_size) {
  759. unsigned int order = __fls(order_mask);
  760. gfp_t alloc_flags = gfp;
  761. order_size = 1U << order;
  762. if (order_mask > order_size)
  763. alloc_flags |= __GFP_NORETRY;
  764. page = alloc_pages_node(nid, alloc_flags, order);
  765. if (!page)
  766. continue;
  767. if (order)
  768. split_page(page, order);
  769. break;
  770. }
  771. if (!page) {
  772. __iommu_dma_free_pages(pages, i);
  773. return NULL;
  774. }
  775. count -= order_size;
  776. while (order_size--)
  777. pages[i++] = page++;
  778. }
  779. return pages;
  780. }
  781. /*
  782. * If size is less than PAGE_SIZE, then a full CPU page will be allocated,
  783. * but an IOMMU which supports smaller pages might not map the whole thing.
  784. */
  785. static struct page **__iommu_dma_alloc_noncontiguous(struct device *dev,
  786. size_t size, struct sg_table *sgt, gfp_t gfp, unsigned long attrs)
  787. {
  788. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  789. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  790. struct iova_domain *iovad = &cookie->iovad;
  791. bool coherent = dev_is_dma_coherent(dev);
  792. int ioprot = dma_info_to_prot(DMA_BIDIRECTIONAL, coherent, attrs);
  793. unsigned int count, min_size, alloc_sizes = domain->pgsize_bitmap;
  794. struct page **pages;
  795. dma_addr_t iova;
  796. ssize_t ret;
  797. if (static_branch_unlikely(&iommu_deferred_attach_enabled) &&
  798. iommu_deferred_attach(dev, domain))
  799. return NULL;
  800. min_size = alloc_sizes & -alloc_sizes;
  801. if (min_size < PAGE_SIZE) {
  802. min_size = PAGE_SIZE;
  803. alloc_sizes |= PAGE_SIZE;
  804. } else {
  805. size = ALIGN(size, min_size);
  806. }
  807. if (attrs & DMA_ATTR_ALLOC_SINGLE_PAGES)
  808. alloc_sizes = min_size;
  809. count = PAGE_ALIGN(size) >> PAGE_SHIFT;
  810. pages = __iommu_dma_alloc_pages(dev, count, alloc_sizes >> PAGE_SHIFT,
  811. gfp);
  812. if (!pages)
  813. return NULL;
  814. size = iova_align(iovad, size);
  815. iova = iommu_dma_alloc_iova(domain, size, dev->coherent_dma_mask, dev);
  816. if (!iova)
  817. goto out_free_pages;
  818. /*
  819. * Remove the zone/policy flags from the GFP - these are applied to the
  820. * __iommu_dma_alloc_pages() but are not used for the supporting
  821. * internal allocations that follow.
  822. */
  823. gfp &= ~(__GFP_DMA | __GFP_DMA32 | __GFP_HIGHMEM | __GFP_COMP);
  824. if (sg_alloc_table_from_pages(sgt, pages, count, 0, size, gfp))
  825. goto out_free_iova;
  826. if (!(ioprot & IOMMU_CACHE)) {
  827. struct scatterlist *sg;
  828. int i;
  829. for_each_sg(sgt->sgl, sg, sgt->orig_nents, i)
  830. arch_dma_prep_coherent(sg_page(sg), sg->length);
  831. }
  832. ret = iommu_map_sg(domain, iova, sgt->sgl, sgt->orig_nents, ioprot,
  833. gfp);
  834. if (ret < 0 || ret < size)
  835. goto out_free_sg;
  836. sgt->sgl->dma_address = iova;
  837. sgt->sgl->dma_length = size;
  838. return pages;
  839. out_free_sg:
  840. sg_free_table(sgt);
  841. out_free_iova:
  842. iommu_dma_free_iova(cookie, iova, size, NULL);
  843. out_free_pages:
  844. __iommu_dma_free_pages(pages, count);
  845. return NULL;
  846. }
  847. static void *iommu_dma_alloc_remap(struct device *dev, size_t size,
  848. dma_addr_t *dma_handle, gfp_t gfp, unsigned long attrs)
  849. {
  850. struct page **pages;
  851. struct sg_table sgt;
  852. void *vaddr;
  853. pgprot_t prot = dma_pgprot(dev, PAGE_KERNEL, attrs);
  854. pages = __iommu_dma_alloc_noncontiguous(dev, size, &sgt, gfp, attrs);
  855. if (!pages)
  856. return NULL;
  857. *dma_handle = sgt.sgl->dma_address;
  858. sg_free_table(&sgt);
  859. vaddr = dma_common_pages_remap(pages, size, prot,
  860. __builtin_return_address(0));
  861. if (!vaddr)
  862. goto out_unmap;
  863. return vaddr;
  864. out_unmap:
  865. __iommu_dma_unmap(dev, *dma_handle, size);
  866. __iommu_dma_free_pages(pages, PAGE_ALIGN(size) >> PAGE_SHIFT);
  867. return NULL;
  868. }
  869. /*
  870. * This is the actual return value from the iommu_dma_alloc_noncontiguous.
  871. *
  872. * The users of the DMA API should only care about the sg_table, but to make
  873. * the DMA-API internal vmaping and freeing easier we stash away the page
  874. * array as well (except for the fallback case). This can go away any time,
  875. * e.g. when a vmap-variant that takes a scatterlist comes along.
  876. */
  877. struct dma_sgt_handle {
  878. struct sg_table sgt;
  879. struct page **pages;
  880. };
  881. #define sgt_handle(sgt) \
  882. container_of((sgt), struct dma_sgt_handle, sgt)
  883. struct sg_table *iommu_dma_alloc_noncontiguous(struct device *dev, size_t size,
  884. enum dma_data_direction dir, gfp_t gfp, unsigned long attrs)
  885. {
  886. struct dma_sgt_handle *sh;
  887. sh = kmalloc(sizeof(*sh), gfp);
  888. if (!sh)
  889. return NULL;
  890. sh->pages = __iommu_dma_alloc_noncontiguous(dev, size, &sh->sgt, gfp, attrs);
  891. if (!sh->pages) {
  892. kfree(sh);
  893. return NULL;
  894. }
  895. return &sh->sgt;
  896. }
  897. void iommu_dma_free_noncontiguous(struct device *dev, size_t size,
  898. struct sg_table *sgt, enum dma_data_direction dir)
  899. {
  900. struct dma_sgt_handle *sh = sgt_handle(sgt);
  901. __iommu_dma_unmap(dev, sgt->sgl->dma_address, size);
  902. __iommu_dma_free_pages(sh->pages, PAGE_ALIGN(size) >> PAGE_SHIFT);
  903. sg_free_table(&sh->sgt);
  904. kfree(sh);
  905. }
  906. void *iommu_dma_vmap_noncontiguous(struct device *dev, size_t size,
  907. struct sg_table *sgt)
  908. {
  909. unsigned long count = PAGE_ALIGN(size) >> PAGE_SHIFT;
  910. return vmap(sgt_handle(sgt)->pages, count, VM_MAP, PAGE_KERNEL);
  911. }
  912. int iommu_dma_mmap_noncontiguous(struct device *dev, struct vm_area_struct *vma,
  913. size_t size, struct sg_table *sgt)
  914. {
  915. unsigned long count = PAGE_ALIGN(size) >> PAGE_SHIFT;
  916. if (vma->vm_pgoff >= count || vma_pages(vma) > count - vma->vm_pgoff)
  917. return -ENXIO;
  918. return vm_map_pages(vma, sgt_handle(sgt)->pages, count);
  919. }
  920. void iommu_dma_sync_single_for_cpu(struct device *dev, dma_addr_t dma_handle,
  921. size_t size, enum dma_data_direction dir)
  922. {
  923. phys_addr_t phys;
  924. if (dev_is_dma_coherent(dev) && !dev_use_swiotlb(dev, size, dir))
  925. return;
  926. phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle);
  927. if (!dev_is_dma_coherent(dev))
  928. arch_sync_dma_for_cpu(phys, size, dir);
  929. swiotlb_sync_single_for_cpu(dev, phys, size, dir);
  930. }
  931. void iommu_dma_sync_single_for_device(struct device *dev, dma_addr_t dma_handle,
  932. size_t size, enum dma_data_direction dir)
  933. {
  934. phys_addr_t phys;
  935. if (dev_is_dma_coherent(dev) && !dev_use_swiotlb(dev, size, dir))
  936. return;
  937. phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle);
  938. swiotlb_sync_single_for_device(dev, phys, size, dir);
  939. if (!dev_is_dma_coherent(dev))
  940. arch_sync_dma_for_device(phys, size, dir);
  941. }
  942. void iommu_dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sgl,
  943. int nelems, enum dma_data_direction dir)
  944. {
  945. struct scatterlist *sg;
  946. int i;
  947. if (sg_dma_is_swiotlb(sgl))
  948. for_each_sg(sgl, sg, nelems, i)
  949. iommu_dma_sync_single_for_cpu(dev, sg_dma_address(sg),
  950. sg->length, dir);
  951. else if (!dev_is_dma_coherent(dev))
  952. for_each_sg(sgl, sg, nelems, i)
  953. arch_sync_dma_for_cpu(sg_phys(sg), sg->length, dir);
  954. }
  955. void iommu_dma_sync_sg_for_device(struct device *dev, struct scatterlist *sgl,
  956. int nelems, enum dma_data_direction dir)
  957. {
  958. struct scatterlist *sg;
  959. int i;
  960. if (sg_dma_is_swiotlb(sgl))
  961. for_each_sg(sgl, sg, nelems, i)
  962. iommu_dma_sync_single_for_device(dev,
  963. sg_dma_address(sg),
  964. sg->length, dir);
  965. else if (!dev_is_dma_coherent(dev))
  966. for_each_sg(sgl, sg, nelems, i)
  967. arch_sync_dma_for_device(sg_phys(sg), sg->length, dir);
  968. }
  969. dma_addr_t iommu_dma_map_page(struct device *dev, struct page *page,
  970. unsigned long offset, size_t size, enum dma_data_direction dir,
  971. unsigned long attrs)
  972. {
  973. phys_addr_t phys = page_to_phys(page) + offset;
  974. bool coherent = dev_is_dma_coherent(dev);
  975. int prot = dma_info_to_prot(dir, coherent, attrs);
  976. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  977. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  978. struct iova_domain *iovad = &cookie->iovad;
  979. dma_addr_t iova, dma_mask = dma_get_mask(dev);
  980. /*
  981. * If both the physical buffer start address and size are
  982. * page aligned, we don't need to use a bounce page.
  983. */
  984. if (dev_use_swiotlb(dev, size, dir) &&
  985. iova_offset(iovad, phys | size)) {
  986. if (!is_swiotlb_active(dev)) {
  987. dev_warn_once(dev, "DMA bounce buffers are inactive, unable to map unaligned transaction.\n");
  988. return DMA_MAPPING_ERROR;
  989. }
  990. trace_swiotlb_bounced(dev, phys, size);
  991. phys = swiotlb_tbl_map_single(dev, phys, size,
  992. iova_mask(iovad), dir, attrs);
  993. if (phys == DMA_MAPPING_ERROR)
  994. return DMA_MAPPING_ERROR;
  995. /*
  996. * Untrusted devices should not see padding areas with random
  997. * leftover kernel data, so zero the pre- and post-padding.
  998. * swiotlb_tbl_map_single() has initialized the bounce buffer
  999. * proper to the contents of the original memory buffer.
  1000. */
  1001. if (dev_is_untrusted(dev)) {
  1002. size_t start, virt = (size_t)phys_to_virt(phys);
  1003. /* Pre-padding */
  1004. start = iova_align_down(iovad, virt);
  1005. memset((void *)start, 0, virt - start);
  1006. /* Post-padding */
  1007. start = virt + size;
  1008. memset((void *)start, 0,
  1009. iova_align(iovad, start) - start);
  1010. }
  1011. }
  1012. if (!coherent && !(attrs & DMA_ATTR_SKIP_CPU_SYNC))
  1013. arch_sync_dma_for_device(phys, size, dir);
  1014. iova = __iommu_dma_map(dev, phys, size, prot, dma_mask);
  1015. if (iova == DMA_MAPPING_ERROR)
  1016. swiotlb_tbl_unmap_single(dev, phys, size, dir, attrs);
  1017. return iova;
  1018. }
  1019. void iommu_dma_unmap_page(struct device *dev, dma_addr_t dma_handle,
  1020. size_t size, enum dma_data_direction dir, unsigned long attrs)
  1021. {
  1022. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  1023. phys_addr_t phys;
  1024. phys = iommu_iova_to_phys(domain, dma_handle);
  1025. if (WARN_ON(!phys))
  1026. return;
  1027. if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) && !dev_is_dma_coherent(dev))
  1028. arch_sync_dma_for_cpu(phys, size, dir);
  1029. __iommu_dma_unmap(dev, dma_handle, size);
  1030. swiotlb_tbl_unmap_single(dev, phys, size, dir, attrs);
  1031. }
  1032. /*
  1033. * Prepare a successfully-mapped scatterlist to give back to the caller.
  1034. *
  1035. * At this point the segments are already laid out by iommu_dma_map_sg() to
  1036. * avoid individually crossing any boundaries, so we merely need to check a
  1037. * segment's start address to avoid concatenating across one.
  1038. */
  1039. static int __finalise_sg(struct device *dev, struct scatterlist *sg, int nents,
  1040. dma_addr_t dma_addr)
  1041. {
  1042. struct scatterlist *s, *cur = sg;
  1043. unsigned long seg_mask = dma_get_seg_boundary(dev);
  1044. unsigned int cur_len = 0, max_len = dma_get_max_seg_size(dev);
  1045. int i, count = 0;
  1046. for_each_sg(sg, s, nents, i) {
  1047. /* Restore this segment's original unaligned fields first */
  1048. dma_addr_t s_dma_addr = sg_dma_address(s);
  1049. unsigned int s_iova_off = sg_dma_address(s);
  1050. unsigned int s_length = sg_dma_len(s);
  1051. unsigned int s_iova_len = s->length;
  1052. sg_dma_address(s) = DMA_MAPPING_ERROR;
  1053. sg_dma_len(s) = 0;
  1054. if (sg_dma_is_bus_address(s)) {
  1055. if (i > 0)
  1056. cur = sg_next(cur);
  1057. sg_dma_unmark_bus_address(s);
  1058. sg_dma_address(cur) = s_dma_addr;
  1059. sg_dma_len(cur) = s_length;
  1060. sg_dma_mark_bus_address(cur);
  1061. count++;
  1062. cur_len = 0;
  1063. continue;
  1064. }
  1065. s->offset += s_iova_off;
  1066. s->length = s_length;
  1067. /*
  1068. * Now fill in the real DMA data. If...
  1069. * - there is a valid output segment to append to
  1070. * - and this segment starts on an IOVA page boundary
  1071. * - but doesn't fall at a segment boundary
  1072. * - and wouldn't make the resulting output segment too long
  1073. */
  1074. if (cur_len && !s_iova_off && (dma_addr & seg_mask) &&
  1075. (max_len - cur_len >= s_length)) {
  1076. /* ...then concatenate it with the previous one */
  1077. cur_len += s_length;
  1078. } else {
  1079. /* Otherwise start the next output segment */
  1080. if (i > 0)
  1081. cur = sg_next(cur);
  1082. cur_len = s_length;
  1083. count++;
  1084. sg_dma_address(cur) = dma_addr + s_iova_off;
  1085. }
  1086. sg_dma_len(cur) = cur_len;
  1087. dma_addr += s_iova_len;
  1088. if (s_length + s_iova_off < s_iova_len)
  1089. cur_len = 0;
  1090. }
  1091. return count;
  1092. }
  1093. /*
  1094. * If mapping failed, then just restore the original list,
  1095. * but making sure the DMA fields are invalidated.
  1096. */
  1097. static void __invalidate_sg(struct scatterlist *sg, int nents)
  1098. {
  1099. struct scatterlist *s;
  1100. int i;
  1101. for_each_sg(sg, s, nents, i) {
  1102. if (sg_dma_is_bus_address(s)) {
  1103. sg_dma_unmark_bus_address(s);
  1104. } else {
  1105. if (sg_dma_address(s) != DMA_MAPPING_ERROR)
  1106. s->offset += sg_dma_address(s);
  1107. if (sg_dma_len(s))
  1108. s->length = sg_dma_len(s);
  1109. }
  1110. sg_dma_address(s) = DMA_MAPPING_ERROR;
  1111. sg_dma_len(s) = 0;
  1112. }
  1113. }
  1114. static void iommu_dma_unmap_sg_swiotlb(struct device *dev, struct scatterlist *sg,
  1115. int nents, enum dma_data_direction dir, unsigned long attrs)
  1116. {
  1117. struct scatterlist *s;
  1118. int i;
  1119. for_each_sg(sg, s, nents, i)
  1120. iommu_dma_unmap_page(dev, sg_dma_address(s),
  1121. sg_dma_len(s), dir, attrs);
  1122. }
  1123. static int iommu_dma_map_sg_swiotlb(struct device *dev, struct scatterlist *sg,
  1124. int nents, enum dma_data_direction dir, unsigned long attrs)
  1125. {
  1126. struct scatterlist *s;
  1127. int i;
  1128. sg_dma_mark_swiotlb(sg);
  1129. for_each_sg(sg, s, nents, i) {
  1130. sg_dma_address(s) = iommu_dma_map_page(dev, sg_page(s),
  1131. s->offset, s->length, dir, attrs);
  1132. if (sg_dma_address(s) == DMA_MAPPING_ERROR)
  1133. goto out_unmap;
  1134. sg_dma_len(s) = s->length;
  1135. }
  1136. return nents;
  1137. out_unmap:
  1138. iommu_dma_unmap_sg_swiotlb(dev, sg, i, dir, attrs | DMA_ATTR_SKIP_CPU_SYNC);
  1139. return -EIO;
  1140. }
  1141. /*
  1142. * The DMA API client is passing in a scatterlist which could describe
  1143. * any old buffer layout, but the IOMMU API requires everything to be
  1144. * aligned to IOMMU pages. Hence the need for this complicated bit of
  1145. * impedance-matching, to be able to hand off a suitably-aligned list,
  1146. * but still preserve the original offsets and sizes for the caller.
  1147. */
  1148. int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
  1149. enum dma_data_direction dir, unsigned long attrs)
  1150. {
  1151. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  1152. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  1153. struct iova_domain *iovad = &cookie->iovad;
  1154. struct scatterlist *s, *prev = NULL;
  1155. int prot = dma_info_to_prot(dir, dev_is_dma_coherent(dev), attrs);
  1156. struct pci_p2pdma_map_state p2pdma_state = {};
  1157. enum pci_p2pdma_map_type map;
  1158. dma_addr_t iova;
  1159. size_t iova_len = 0;
  1160. unsigned long mask = dma_get_seg_boundary(dev);
  1161. ssize_t ret;
  1162. int i;
  1163. if (static_branch_unlikely(&iommu_deferred_attach_enabled)) {
  1164. ret = iommu_deferred_attach(dev, domain);
  1165. if (ret)
  1166. goto out;
  1167. }
  1168. if (dev_use_sg_swiotlb(dev, sg, nents, dir))
  1169. return iommu_dma_map_sg_swiotlb(dev, sg, nents, dir, attrs);
  1170. if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
  1171. iommu_dma_sync_sg_for_device(dev, sg, nents, dir);
  1172. /*
  1173. * Work out how much IOVA space we need, and align the segments to
  1174. * IOVA granules for the IOMMU driver to handle. With some clever
  1175. * trickery we can modify the list in-place, but reversibly, by
  1176. * stashing the unaligned parts in the as-yet-unused DMA fields.
  1177. */
  1178. for_each_sg(sg, s, nents, i) {
  1179. size_t s_iova_off = iova_offset(iovad, s->offset);
  1180. size_t s_length = s->length;
  1181. size_t pad_len = (mask - iova_len + 1) & mask;
  1182. if (is_pci_p2pdma_page(sg_page(s))) {
  1183. map = pci_p2pdma_map_segment(&p2pdma_state, dev, s);
  1184. switch (map) {
  1185. case PCI_P2PDMA_MAP_BUS_ADDR:
  1186. /*
  1187. * iommu_map_sg() will skip this segment as
  1188. * it is marked as a bus address,
  1189. * __finalise_sg() will copy the dma address
  1190. * into the output segment.
  1191. */
  1192. continue;
  1193. case PCI_P2PDMA_MAP_THRU_HOST_BRIDGE:
  1194. /*
  1195. * Mapping through host bridge should be
  1196. * mapped with regular IOVAs, thus we
  1197. * do nothing here and continue below.
  1198. */
  1199. break;
  1200. default:
  1201. ret = -EREMOTEIO;
  1202. goto out_restore_sg;
  1203. }
  1204. }
  1205. sg_dma_address(s) = s_iova_off;
  1206. sg_dma_len(s) = s_length;
  1207. s->offset -= s_iova_off;
  1208. s_length = iova_align(iovad, s_length + s_iova_off);
  1209. s->length = s_length;
  1210. /*
  1211. * Due to the alignment of our single IOVA allocation, we can
  1212. * depend on these assumptions about the segment boundary mask:
  1213. * - If mask size >= IOVA size, then the IOVA range cannot
  1214. * possibly fall across a boundary, so we don't care.
  1215. * - If mask size < IOVA size, then the IOVA range must start
  1216. * exactly on a boundary, therefore we can lay things out
  1217. * based purely on segment lengths without needing to know
  1218. * the actual addresses beforehand.
  1219. * - The mask must be a power of 2, so pad_len == 0 if
  1220. * iova_len == 0, thus we cannot dereference prev the first
  1221. * time through here (i.e. before it has a meaningful value).
  1222. */
  1223. if (pad_len && pad_len < s_length - 1) {
  1224. prev->length += pad_len;
  1225. iova_len += pad_len;
  1226. }
  1227. iova_len += s_length;
  1228. prev = s;
  1229. }
  1230. if (!iova_len)
  1231. return __finalise_sg(dev, sg, nents, 0);
  1232. iova = iommu_dma_alloc_iova(domain, iova_len, dma_get_mask(dev), dev);
  1233. if (!iova) {
  1234. ret = -ENOMEM;
  1235. goto out_restore_sg;
  1236. }
  1237. /*
  1238. * We'll leave any physical concatenation to the IOMMU driver's
  1239. * implementation - it knows better than we do.
  1240. */
  1241. ret = iommu_map_sg(domain, iova, sg, nents, prot, GFP_ATOMIC);
  1242. if (ret < 0 || ret < iova_len)
  1243. goto out_free_iova;
  1244. return __finalise_sg(dev, sg, nents, iova);
  1245. out_free_iova:
  1246. iommu_dma_free_iova(cookie, iova, iova_len, NULL);
  1247. out_restore_sg:
  1248. __invalidate_sg(sg, nents);
  1249. out:
  1250. if (ret != -ENOMEM && ret != -EREMOTEIO)
  1251. return -EINVAL;
  1252. return ret;
  1253. }
  1254. void iommu_dma_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
  1255. enum dma_data_direction dir, unsigned long attrs)
  1256. {
  1257. dma_addr_t end = 0, start;
  1258. struct scatterlist *tmp;
  1259. int i;
  1260. if (sg_dma_is_swiotlb(sg)) {
  1261. iommu_dma_unmap_sg_swiotlb(dev, sg, nents, dir, attrs);
  1262. return;
  1263. }
  1264. if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
  1265. iommu_dma_sync_sg_for_cpu(dev, sg, nents, dir);
  1266. /*
  1267. * The scatterlist segments are mapped into a single
  1268. * contiguous IOVA allocation, the start and end points
  1269. * just have to be determined.
  1270. */
  1271. for_each_sg(sg, tmp, nents, i) {
  1272. if (sg_dma_is_bus_address(tmp)) {
  1273. sg_dma_unmark_bus_address(tmp);
  1274. continue;
  1275. }
  1276. if (sg_dma_len(tmp) == 0)
  1277. break;
  1278. start = sg_dma_address(tmp);
  1279. break;
  1280. }
  1281. nents -= i;
  1282. for_each_sg(tmp, tmp, nents, i) {
  1283. if (sg_dma_is_bus_address(tmp)) {
  1284. sg_dma_unmark_bus_address(tmp);
  1285. continue;
  1286. }
  1287. if (sg_dma_len(tmp) == 0)
  1288. break;
  1289. end = sg_dma_address(tmp) + sg_dma_len(tmp);
  1290. }
  1291. if (end)
  1292. __iommu_dma_unmap(dev, start, end - start);
  1293. }
  1294. dma_addr_t iommu_dma_map_resource(struct device *dev, phys_addr_t phys,
  1295. size_t size, enum dma_data_direction dir, unsigned long attrs)
  1296. {
  1297. return __iommu_dma_map(dev, phys, size,
  1298. dma_info_to_prot(dir, false, attrs) | IOMMU_MMIO,
  1299. dma_get_mask(dev));
  1300. }
  1301. void iommu_dma_unmap_resource(struct device *dev, dma_addr_t handle,
  1302. size_t size, enum dma_data_direction dir, unsigned long attrs)
  1303. {
  1304. __iommu_dma_unmap(dev, handle, size);
  1305. }
  1306. static void __iommu_dma_free(struct device *dev, size_t size, void *cpu_addr)
  1307. {
  1308. size_t alloc_size = PAGE_ALIGN(size);
  1309. int count = alloc_size >> PAGE_SHIFT;
  1310. struct page *page = NULL, **pages = NULL;
  1311. /* Non-coherent atomic allocation? Easy */
  1312. if (IS_ENABLED(CONFIG_DMA_DIRECT_REMAP) &&
  1313. dma_free_from_pool(dev, cpu_addr, alloc_size))
  1314. return;
  1315. if (is_vmalloc_addr(cpu_addr)) {
  1316. /*
  1317. * If it the address is remapped, then it's either non-coherent
  1318. * or highmem CMA, or an iommu_dma_alloc_remap() construction.
  1319. */
  1320. pages = dma_common_find_pages(cpu_addr);
  1321. if (!pages)
  1322. page = vmalloc_to_page(cpu_addr);
  1323. dma_common_free_remap(cpu_addr, alloc_size);
  1324. } else {
  1325. /* Lowmem means a coherent atomic or CMA allocation */
  1326. page = virt_to_page(cpu_addr);
  1327. }
  1328. if (pages)
  1329. __iommu_dma_free_pages(pages, count);
  1330. if (page)
  1331. dma_free_contiguous(dev, page, alloc_size);
  1332. }
  1333. void iommu_dma_free(struct device *dev, size_t size, void *cpu_addr,
  1334. dma_addr_t handle, unsigned long attrs)
  1335. {
  1336. __iommu_dma_unmap(dev, handle, size);
  1337. __iommu_dma_free(dev, size, cpu_addr);
  1338. }
  1339. static void *iommu_dma_alloc_pages(struct device *dev, size_t size,
  1340. struct page **pagep, gfp_t gfp, unsigned long attrs)
  1341. {
  1342. bool coherent = dev_is_dma_coherent(dev);
  1343. size_t alloc_size = PAGE_ALIGN(size);
  1344. int node = dev_to_node(dev);
  1345. struct page *page = NULL;
  1346. void *cpu_addr;
  1347. page = dma_alloc_contiguous(dev, alloc_size, gfp);
  1348. if (!page)
  1349. page = alloc_pages_node(node, gfp, get_order(alloc_size));
  1350. if (!page)
  1351. return NULL;
  1352. if (!coherent || PageHighMem(page)) {
  1353. pgprot_t prot = dma_pgprot(dev, PAGE_KERNEL, attrs);
  1354. cpu_addr = dma_common_contiguous_remap(page, alloc_size,
  1355. prot, __builtin_return_address(0));
  1356. if (!cpu_addr)
  1357. goto out_free_pages;
  1358. if (!coherent)
  1359. arch_dma_prep_coherent(page, size);
  1360. } else {
  1361. cpu_addr = page_address(page);
  1362. }
  1363. *pagep = page;
  1364. memset(cpu_addr, 0, alloc_size);
  1365. return cpu_addr;
  1366. out_free_pages:
  1367. dma_free_contiguous(dev, page, alloc_size);
  1368. return NULL;
  1369. }
  1370. void *iommu_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
  1371. gfp_t gfp, unsigned long attrs)
  1372. {
  1373. bool coherent = dev_is_dma_coherent(dev);
  1374. int ioprot = dma_info_to_prot(DMA_BIDIRECTIONAL, coherent, attrs);
  1375. struct page *page = NULL;
  1376. void *cpu_addr;
  1377. gfp |= __GFP_ZERO;
  1378. if (gfpflags_allow_blocking(gfp) &&
  1379. !(attrs & DMA_ATTR_FORCE_CONTIGUOUS)) {
  1380. return iommu_dma_alloc_remap(dev, size, handle, gfp, attrs);
  1381. }
  1382. if (IS_ENABLED(CONFIG_DMA_DIRECT_REMAP) &&
  1383. !gfpflags_allow_blocking(gfp) && !coherent)
  1384. page = dma_alloc_from_pool(dev, PAGE_ALIGN(size), &cpu_addr,
  1385. gfp, NULL);
  1386. else
  1387. cpu_addr = iommu_dma_alloc_pages(dev, size, &page, gfp, attrs);
  1388. if (!cpu_addr)
  1389. return NULL;
  1390. *handle = __iommu_dma_map(dev, page_to_phys(page), size, ioprot,
  1391. dev->coherent_dma_mask);
  1392. if (*handle == DMA_MAPPING_ERROR) {
  1393. __iommu_dma_free(dev, size, cpu_addr);
  1394. return NULL;
  1395. }
  1396. return cpu_addr;
  1397. }
  1398. int iommu_dma_mmap(struct device *dev, struct vm_area_struct *vma,
  1399. void *cpu_addr, dma_addr_t dma_addr, size_t size,
  1400. unsigned long attrs)
  1401. {
  1402. unsigned long nr_pages = PAGE_ALIGN(size) >> PAGE_SHIFT;
  1403. unsigned long pfn, off = vma->vm_pgoff;
  1404. int ret;
  1405. vma->vm_page_prot = dma_pgprot(dev, vma->vm_page_prot, attrs);
  1406. if (dma_mmap_from_dev_coherent(dev, vma, cpu_addr, size, &ret))
  1407. return ret;
  1408. if (off >= nr_pages || vma_pages(vma) > nr_pages - off)
  1409. return -ENXIO;
  1410. if (is_vmalloc_addr(cpu_addr)) {
  1411. struct page **pages = dma_common_find_pages(cpu_addr);
  1412. if (pages)
  1413. return vm_map_pages(vma, pages, nr_pages);
  1414. pfn = vmalloc_to_pfn(cpu_addr);
  1415. } else {
  1416. pfn = page_to_pfn(virt_to_page(cpu_addr));
  1417. }
  1418. return remap_pfn_range(vma, vma->vm_start, pfn + off,
  1419. vma->vm_end - vma->vm_start,
  1420. vma->vm_page_prot);
  1421. }
  1422. int iommu_dma_get_sgtable(struct device *dev, struct sg_table *sgt,
  1423. void *cpu_addr, dma_addr_t dma_addr, size_t size,
  1424. unsigned long attrs)
  1425. {
  1426. struct page *page;
  1427. int ret;
  1428. if (is_vmalloc_addr(cpu_addr)) {
  1429. struct page **pages = dma_common_find_pages(cpu_addr);
  1430. if (pages) {
  1431. return sg_alloc_table_from_pages(sgt, pages,
  1432. PAGE_ALIGN(size) >> PAGE_SHIFT,
  1433. 0, size, GFP_KERNEL);
  1434. }
  1435. page = vmalloc_to_page(cpu_addr);
  1436. } else {
  1437. page = virt_to_page(cpu_addr);
  1438. }
  1439. ret = sg_alloc_table(sgt, 1, GFP_KERNEL);
  1440. if (!ret)
  1441. sg_set_page(sgt->sgl, page, PAGE_ALIGN(size), 0);
  1442. return ret;
  1443. }
  1444. unsigned long iommu_dma_get_merge_boundary(struct device *dev)
  1445. {
  1446. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  1447. return (1UL << __ffs(domain->pgsize_bitmap)) - 1;
  1448. }
  1449. size_t iommu_dma_opt_mapping_size(void)
  1450. {
  1451. return iova_rcache_range();
  1452. }
  1453. size_t iommu_dma_max_mapping_size(struct device *dev)
  1454. {
  1455. if (dev_is_untrusted(dev))
  1456. return swiotlb_max_mapping_size(dev);
  1457. return SIZE_MAX;
  1458. }
  1459. void iommu_setup_dma_ops(struct device *dev)
  1460. {
  1461. struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
  1462. if (dev_is_pci(dev))
  1463. dev->iommu->pci_32bit_workaround = !iommu_dma_forcedac;
  1464. dev->dma_iommu = iommu_is_dma_domain(domain);
  1465. if (dev->dma_iommu && iommu_dma_init_domain(domain, dev))
  1466. goto out_err;
  1467. return;
  1468. out_err:
  1469. pr_warn("Failed to set up IOMMU for device %s; retaining platform DMA ops\n",
  1470. dev_name(dev));
  1471. dev->dma_iommu = false;
  1472. }
  1473. static struct iommu_dma_msi_page *iommu_dma_get_msi_page(struct device *dev,
  1474. phys_addr_t msi_addr, struct iommu_domain *domain)
  1475. {
  1476. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  1477. struct iommu_dma_msi_page *msi_page;
  1478. dma_addr_t iova;
  1479. int prot = IOMMU_WRITE | IOMMU_NOEXEC | IOMMU_MMIO;
  1480. size_t size = cookie_msi_granule(cookie);
  1481. msi_addr &= ~(phys_addr_t)(size - 1);
  1482. list_for_each_entry(msi_page, &cookie->msi_page_list, list)
  1483. if (msi_page->phys == msi_addr)
  1484. return msi_page;
  1485. msi_page = kzalloc(sizeof(*msi_page), GFP_KERNEL);
  1486. if (!msi_page)
  1487. return NULL;
  1488. iova = iommu_dma_alloc_iova(domain, size, dma_get_mask(dev), dev);
  1489. if (!iova)
  1490. goto out_free_page;
  1491. if (iommu_map(domain, iova, msi_addr, size, prot, GFP_KERNEL))
  1492. goto out_free_iova;
  1493. INIT_LIST_HEAD(&msi_page->list);
  1494. msi_page->phys = msi_addr;
  1495. msi_page->iova = iova;
  1496. list_add(&msi_page->list, &cookie->msi_page_list);
  1497. return msi_page;
  1498. out_free_iova:
  1499. iommu_dma_free_iova(cookie, iova, size, NULL);
  1500. out_free_page:
  1501. kfree(msi_page);
  1502. return NULL;
  1503. }
  1504. /**
  1505. * iommu_dma_prepare_msi() - Map the MSI page in the IOMMU domain
  1506. * @desc: MSI descriptor, will store the MSI page
  1507. * @msi_addr: MSI target address to be mapped
  1508. *
  1509. * Return: 0 on success or negative error code if the mapping failed.
  1510. */
  1511. int iommu_dma_prepare_msi(struct msi_desc *desc, phys_addr_t msi_addr)
  1512. {
  1513. struct device *dev = msi_desc_to_dev(desc);
  1514. struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
  1515. struct iommu_dma_msi_page *msi_page;
  1516. static DEFINE_MUTEX(msi_prepare_lock); /* see below */
  1517. if (!domain || !domain->iova_cookie) {
  1518. msi_desc_set_iommu_msi_iova(desc, 0, 0);
  1519. return 0;
  1520. }
  1521. /*
  1522. * In fact the whole prepare operation should already be serialised by
  1523. * irq_domain_mutex further up the callchain, but that's pretty subtle
  1524. * on its own, so consider this locking as failsafe documentation...
  1525. */
  1526. mutex_lock(&msi_prepare_lock);
  1527. msi_page = iommu_dma_get_msi_page(dev, msi_addr, domain);
  1528. mutex_unlock(&msi_prepare_lock);
  1529. if (!msi_page)
  1530. return -ENOMEM;
  1531. msi_desc_set_iommu_msi_iova(
  1532. desc, msi_page->iova,
  1533. ilog2(cookie_msi_granule(domain->iova_cookie)));
  1534. return 0;
  1535. }
  1536. /**
  1537. * iommu_dma_compose_msi_msg() - Apply translation to an MSI message
  1538. * @desc: MSI descriptor prepared by iommu_dma_prepare_msi()
  1539. * @msg: MSI message containing target physical address
  1540. */
  1541. void iommu_dma_compose_msi_msg(struct msi_desc *desc, struct msi_msg *msg)
  1542. {
  1543. #ifdef CONFIG_IRQ_MSI_IOMMU
  1544. if (desc->iommu_msi_shift) {
  1545. u64 msi_iova = desc->iommu_msi_iova << desc->iommu_msi_shift;
  1546. msg->address_hi = upper_32_bits(msi_iova);
  1547. msg->address_lo = lower_32_bits(msi_iova) |
  1548. (msg->address_lo & ((1 << desc->iommu_msi_shift) - 1));
  1549. }
  1550. #endif
  1551. }
  1552. static int iommu_dma_init(void)
  1553. {
  1554. if (is_kdump_kernel())
  1555. static_branch_enable(&iommu_deferred_attach_enabled);
  1556. return iova_cache_get();
  1557. }
  1558. arch_initcall(iommu_dma_init);