dma-iommu.c 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225
  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/msi.h>
  27. #include <linux/of_iommu.h>
  28. #include <linux/pci.h>
  29. #include <linux/pci-p2pdma.h>
  30. #include <linux/scatterlist.h>
  31. #include <linux/spinlock.h>
  32. #include <linux/swiotlb.h>
  33. #include <linux/vmalloc.h>
  34. #include <trace/events/swiotlb.h>
  35. #include "dma-iommu.h"
  36. #include "iommu-pages.h"
  37. struct iommu_dma_msi_page {
  38. struct list_head list;
  39. dma_addr_t iova;
  40. phys_addr_t phys;
  41. };
  42. enum iommu_dma_queue_type {
  43. IOMMU_DMA_OPTS_PER_CPU_QUEUE,
  44. IOMMU_DMA_OPTS_SINGLE_QUEUE,
  45. };
  46. struct iommu_dma_options {
  47. enum iommu_dma_queue_type qt;
  48. size_t fq_size;
  49. unsigned int fq_timeout;
  50. };
  51. struct iommu_dma_cookie {
  52. struct iova_domain iovad;
  53. struct list_head msi_page_list;
  54. /* Flush queue */
  55. union {
  56. struct iova_fq *single_fq;
  57. struct iova_fq __percpu *percpu_fq;
  58. };
  59. /* Number of TLB flushes that have been started */
  60. atomic64_t fq_flush_start_cnt;
  61. /* Number of TLB flushes that have been finished */
  62. atomic64_t fq_flush_finish_cnt;
  63. /* Timer to regularily empty the flush queues */
  64. struct timer_list fq_timer;
  65. /* 1 when timer is active, 0 when not */
  66. atomic_t fq_timer_on;
  67. /* Domain for flush queue callback; NULL if flush queue not in use */
  68. struct iommu_domain *fq_domain;
  69. /* Options for dma-iommu use */
  70. struct iommu_dma_options options;
  71. };
  72. struct iommu_dma_msi_cookie {
  73. dma_addr_t msi_iova;
  74. struct list_head msi_page_list;
  75. };
  76. static DEFINE_STATIC_KEY_FALSE(iommu_deferred_attach_enabled);
  77. bool iommu_dma_forcedac __read_mostly;
  78. static int __init iommu_dma_forcedac_setup(char *str)
  79. {
  80. int ret = kstrtobool(str, &iommu_dma_forcedac);
  81. if (!ret && iommu_dma_forcedac)
  82. pr_info("Forcing DAC for PCI devices\n");
  83. return ret;
  84. }
  85. early_param("iommu.forcedac", iommu_dma_forcedac_setup);
  86. /* Number of entries per flush queue */
  87. #define IOVA_DEFAULT_FQ_SIZE 256
  88. #define IOVA_SINGLE_FQ_SIZE 32768
  89. /* Timeout (in ms) after which entries are flushed from the queue */
  90. #define IOVA_DEFAULT_FQ_TIMEOUT 10
  91. #define IOVA_SINGLE_FQ_TIMEOUT 1000
  92. /* Flush queue entry for deferred flushing */
  93. struct iova_fq_entry {
  94. unsigned long iova_pfn;
  95. unsigned long pages;
  96. struct iommu_pages_list freelist;
  97. u64 counter; /* Flush counter when this entry was added */
  98. };
  99. /* Per-CPU flush queue structure */
  100. struct iova_fq {
  101. spinlock_t lock;
  102. unsigned int head, tail;
  103. unsigned int mod_mask;
  104. struct iova_fq_entry entries[];
  105. };
  106. #define fq_ring_for_each(i, fq) \
  107. for ((i) = (fq)->head; (i) != (fq)->tail; (i) = ((i) + 1) & (fq)->mod_mask)
  108. static inline bool fq_full(struct iova_fq *fq)
  109. {
  110. assert_spin_locked(&fq->lock);
  111. return (((fq->tail + 1) & fq->mod_mask) == fq->head);
  112. }
  113. static inline unsigned int fq_ring_add(struct iova_fq *fq)
  114. {
  115. unsigned int idx = fq->tail;
  116. assert_spin_locked(&fq->lock);
  117. fq->tail = (idx + 1) & fq->mod_mask;
  118. return idx;
  119. }
  120. static void fq_ring_free_locked(struct iommu_dma_cookie *cookie, struct iova_fq *fq)
  121. {
  122. u64 counter = atomic64_read(&cookie->fq_flush_finish_cnt);
  123. unsigned int idx;
  124. assert_spin_locked(&fq->lock);
  125. fq_ring_for_each(idx, fq) {
  126. if (fq->entries[idx].counter >= counter)
  127. break;
  128. iommu_put_pages_list(&fq->entries[idx].freelist);
  129. free_iova_fast(&cookie->iovad,
  130. fq->entries[idx].iova_pfn,
  131. fq->entries[idx].pages);
  132. fq->entries[idx].freelist =
  133. IOMMU_PAGES_LIST_INIT(fq->entries[idx].freelist);
  134. fq->head = (fq->head + 1) & fq->mod_mask;
  135. }
  136. }
  137. static void fq_ring_free(struct iommu_dma_cookie *cookie, struct iova_fq *fq)
  138. {
  139. unsigned long flags;
  140. spin_lock_irqsave(&fq->lock, flags);
  141. fq_ring_free_locked(cookie, fq);
  142. spin_unlock_irqrestore(&fq->lock, flags);
  143. }
  144. static void fq_flush_iotlb(struct iommu_dma_cookie *cookie)
  145. {
  146. atomic64_inc(&cookie->fq_flush_start_cnt);
  147. cookie->fq_domain->ops->flush_iotlb_all(cookie->fq_domain);
  148. atomic64_inc(&cookie->fq_flush_finish_cnt);
  149. }
  150. static void fq_flush_timeout(struct timer_list *t)
  151. {
  152. struct iommu_dma_cookie *cookie = timer_container_of(cookie, t,
  153. fq_timer);
  154. int cpu;
  155. atomic_set(&cookie->fq_timer_on, 0);
  156. fq_flush_iotlb(cookie);
  157. if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE) {
  158. fq_ring_free(cookie, cookie->single_fq);
  159. } else {
  160. for_each_possible_cpu(cpu)
  161. fq_ring_free(cookie, per_cpu_ptr(cookie->percpu_fq, cpu));
  162. }
  163. }
  164. static void queue_iova(struct iommu_dma_cookie *cookie,
  165. unsigned long pfn, unsigned long pages,
  166. struct iommu_pages_list *freelist)
  167. {
  168. struct iova_fq *fq;
  169. unsigned long flags;
  170. unsigned int idx;
  171. /*
  172. * Order against the IOMMU driver's pagetable update from unmapping
  173. * @pte, to guarantee that fq_flush_iotlb() observes that if called
  174. * from a different CPU before we release the lock below. Full barrier
  175. * so it also pairs with iommu_dma_init_fq() to avoid seeing partially
  176. * written fq state here.
  177. */
  178. smp_mb();
  179. if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE)
  180. fq = cookie->single_fq;
  181. else
  182. fq = raw_cpu_ptr(cookie->percpu_fq);
  183. spin_lock_irqsave(&fq->lock, flags);
  184. /*
  185. * First remove all entries from the flush queue that have already been
  186. * flushed out on another CPU. This makes the fq_full() check below less
  187. * likely to be true.
  188. */
  189. fq_ring_free_locked(cookie, fq);
  190. if (fq_full(fq)) {
  191. fq_flush_iotlb(cookie);
  192. fq_ring_free_locked(cookie, fq);
  193. }
  194. idx = fq_ring_add(fq);
  195. fq->entries[idx].iova_pfn = pfn;
  196. fq->entries[idx].pages = pages;
  197. fq->entries[idx].counter = atomic64_read(&cookie->fq_flush_start_cnt);
  198. iommu_pages_list_splice(freelist, &fq->entries[idx].freelist);
  199. spin_unlock_irqrestore(&fq->lock, flags);
  200. /* Avoid false sharing as much as possible. */
  201. if (!atomic_read(&cookie->fq_timer_on) &&
  202. !atomic_xchg(&cookie->fq_timer_on, 1))
  203. mod_timer(&cookie->fq_timer,
  204. jiffies + msecs_to_jiffies(cookie->options.fq_timeout));
  205. }
  206. static void iommu_dma_free_fq_single(struct iova_fq *fq)
  207. {
  208. int idx;
  209. fq_ring_for_each(idx, fq)
  210. iommu_put_pages_list(&fq->entries[idx].freelist);
  211. vfree(fq);
  212. }
  213. static void iommu_dma_free_fq_percpu(struct iova_fq __percpu *percpu_fq)
  214. {
  215. int cpu, idx;
  216. /* The IOVAs will be torn down separately, so just free our queued pages */
  217. for_each_possible_cpu(cpu) {
  218. struct iova_fq *fq = per_cpu_ptr(percpu_fq, cpu);
  219. fq_ring_for_each(idx, fq)
  220. iommu_put_pages_list(&fq->entries[idx].freelist);
  221. }
  222. free_percpu(percpu_fq);
  223. }
  224. static void iommu_dma_free_fq(struct iommu_dma_cookie *cookie)
  225. {
  226. if (!cookie->fq_domain)
  227. return;
  228. timer_delete_sync(&cookie->fq_timer);
  229. if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE)
  230. iommu_dma_free_fq_single(cookie->single_fq);
  231. else
  232. iommu_dma_free_fq_percpu(cookie->percpu_fq);
  233. }
  234. static void iommu_dma_init_one_fq(struct iova_fq *fq, size_t fq_size)
  235. {
  236. int i;
  237. fq->head = 0;
  238. fq->tail = 0;
  239. fq->mod_mask = fq_size - 1;
  240. spin_lock_init(&fq->lock);
  241. for (i = 0; i < fq_size; i++)
  242. fq->entries[i].freelist =
  243. IOMMU_PAGES_LIST_INIT(fq->entries[i].freelist);
  244. }
  245. static int iommu_dma_init_fq_single(struct iommu_dma_cookie *cookie)
  246. {
  247. size_t fq_size = cookie->options.fq_size;
  248. struct iova_fq *queue;
  249. queue = vmalloc(struct_size(queue, entries, fq_size));
  250. if (!queue)
  251. return -ENOMEM;
  252. iommu_dma_init_one_fq(queue, fq_size);
  253. cookie->single_fq = queue;
  254. return 0;
  255. }
  256. static int iommu_dma_init_fq_percpu(struct iommu_dma_cookie *cookie)
  257. {
  258. size_t fq_size = cookie->options.fq_size;
  259. struct iova_fq __percpu *queue;
  260. int cpu;
  261. queue = __alloc_percpu(struct_size(queue, entries, fq_size),
  262. __alignof__(*queue));
  263. if (!queue)
  264. return -ENOMEM;
  265. for_each_possible_cpu(cpu)
  266. iommu_dma_init_one_fq(per_cpu_ptr(queue, cpu), fq_size);
  267. cookie->percpu_fq = queue;
  268. return 0;
  269. }
  270. /* sysfs updates are serialised by the mutex of the group owning @domain */
  271. int iommu_dma_init_fq(struct iommu_domain *domain)
  272. {
  273. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  274. int rc;
  275. if (cookie->fq_domain)
  276. return 0;
  277. atomic64_set(&cookie->fq_flush_start_cnt, 0);
  278. atomic64_set(&cookie->fq_flush_finish_cnt, 0);
  279. if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE)
  280. rc = iommu_dma_init_fq_single(cookie);
  281. else
  282. rc = iommu_dma_init_fq_percpu(cookie);
  283. if (rc) {
  284. pr_warn("iova flush queue initialization failed\n");
  285. return -ENOMEM;
  286. }
  287. timer_setup(&cookie->fq_timer, fq_flush_timeout, 0);
  288. atomic_set(&cookie->fq_timer_on, 0);
  289. /*
  290. * Prevent incomplete fq state being observable. Pairs with path from
  291. * __iommu_dma_unmap() through iommu_dma_free_iova() to queue_iova()
  292. */
  293. smp_wmb();
  294. WRITE_ONCE(cookie->fq_domain, domain);
  295. return 0;
  296. }
  297. /**
  298. * iommu_get_dma_cookie - Acquire DMA-API resources for a domain
  299. * @domain: IOMMU domain to prepare for DMA-API usage
  300. */
  301. int iommu_get_dma_cookie(struct iommu_domain *domain)
  302. {
  303. struct iommu_dma_cookie *cookie;
  304. if (domain->cookie_type != IOMMU_COOKIE_NONE)
  305. return -EEXIST;
  306. cookie = kzalloc_obj(*cookie);
  307. if (!cookie)
  308. return -ENOMEM;
  309. INIT_LIST_HEAD(&cookie->msi_page_list);
  310. domain->cookie_type = IOMMU_COOKIE_DMA_IOVA;
  311. domain->iova_cookie = cookie;
  312. return 0;
  313. }
  314. /**
  315. * iommu_get_msi_cookie - Acquire just MSI remapping resources
  316. * @domain: IOMMU domain to prepare
  317. * @base: Start address of IOVA region for MSI mappings
  318. *
  319. * Users who manage their own IOVA allocation and do not want DMA API support,
  320. * but would still like to take advantage of automatic MSI remapping, can use
  321. * this to initialise their own domain appropriately. Users should reserve a
  322. * contiguous IOVA region, starting at @base, large enough to accommodate the
  323. * number of PAGE_SIZE mappings necessary to cover every MSI doorbell address
  324. * used by the devices attached to @domain.
  325. */
  326. int iommu_get_msi_cookie(struct iommu_domain *domain, dma_addr_t base)
  327. {
  328. struct iommu_dma_msi_cookie *cookie;
  329. if (domain->type != IOMMU_DOMAIN_UNMANAGED)
  330. return -EINVAL;
  331. if (domain->cookie_type != IOMMU_COOKIE_NONE)
  332. return -EEXIST;
  333. cookie = kzalloc_obj(*cookie);
  334. if (!cookie)
  335. return -ENOMEM;
  336. cookie->msi_iova = base;
  337. INIT_LIST_HEAD(&cookie->msi_page_list);
  338. domain->cookie_type = IOMMU_COOKIE_DMA_MSI;
  339. domain->msi_cookie = cookie;
  340. return 0;
  341. }
  342. EXPORT_SYMBOL(iommu_get_msi_cookie);
  343. /**
  344. * iommu_put_dma_cookie - Release a domain's DMA mapping resources
  345. * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie()
  346. */
  347. void iommu_put_dma_cookie(struct iommu_domain *domain)
  348. {
  349. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  350. struct iommu_dma_msi_page *msi, *tmp;
  351. if (cookie->iovad.granule) {
  352. iommu_dma_free_fq(cookie);
  353. put_iova_domain(&cookie->iovad);
  354. }
  355. list_for_each_entry_safe(msi, tmp, &cookie->msi_page_list, list)
  356. kfree(msi);
  357. kfree(cookie);
  358. }
  359. /**
  360. * iommu_put_msi_cookie - Release a domain's MSI mapping resources
  361. * @domain: IOMMU domain previously prepared by iommu_get_msi_cookie()
  362. */
  363. void iommu_put_msi_cookie(struct iommu_domain *domain)
  364. {
  365. struct iommu_dma_msi_cookie *cookie = domain->msi_cookie;
  366. struct iommu_dma_msi_page *msi, *tmp;
  367. list_for_each_entry_safe(msi, tmp, &cookie->msi_page_list, list)
  368. kfree(msi);
  369. kfree(cookie);
  370. }
  371. /**
  372. * iommu_dma_get_resv_regions - Reserved region driver helper
  373. * @dev: Device from iommu_get_resv_regions()
  374. * @list: Reserved region list from iommu_get_resv_regions()
  375. *
  376. * IOMMU drivers can use this to implement their .get_resv_regions callback
  377. * for general non-IOMMU-specific reservations. Currently, this covers GICv3
  378. * ITS region reservation on ACPI based ARM platforms that may require HW MSI
  379. * reservation.
  380. */
  381. void iommu_dma_get_resv_regions(struct device *dev, struct list_head *list)
  382. {
  383. if (!is_of_node(dev_iommu_fwspec_get(dev)->iommu_fwnode))
  384. iort_iommu_get_resv_regions(dev, list);
  385. if (dev->of_node)
  386. of_iommu_get_resv_regions(dev, list);
  387. }
  388. EXPORT_SYMBOL(iommu_dma_get_resv_regions);
  389. static int cookie_init_hw_msi_region(struct iommu_dma_cookie *cookie,
  390. phys_addr_t start, phys_addr_t end)
  391. {
  392. struct iova_domain *iovad = &cookie->iovad;
  393. struct iommu_dma_msi_page *msi_page;
  394. int i, num_pages;
  395. start -= iova_offset(iovad, start);
  396. num_pages = iova_align(iovad, end - start) >> iova_shift(iovad);
  397. for (i = 0; i < num_pages; i++) {
  398. msi_page = kmalloc_obj(*msi_page);
  399. if (!msi_page)
  400. return -ENOMEM;
  401. msi_page->phys = start;
  402. msi_page->iova = start;
  403. INIT_LIST_HEAD(&msi_page->list);
  404. list_add(&msi_page->list, &cookie->msi_page_list);
  405. start += iovad->granule;
  406. }
  407. return 0;
  408. }
  409. static int iommu_dma_ranges_sort(void *priv, const struct list_head *a,
  410. const struct list_head *b)
  411. {
  412. struct resource_entry *res_a = list_entry(a, typeof(*res_a), node);
  413. struct resource_entry *res_b = list_entry(b, typeof(*res_b), node);
  414. return res_a->res->start > res_b->res->start;
  415. }
  416. static int iova_reserve_pci_windows(struct pci_dev *dev,
  417. struct iova_domain *iovad)
  418. {
  419. struct pci_host_bridge *bridge = pci_find_host_bridge(dev->bus);
  420. struct resource_entry *window;
  421. unsigned long lo, hi;
  422. phys_addr_t start = 0, end;
  423. resource_list_for_each_entry(window, &bridge->windows) {
  424. if (resource_type(window->res) != IORESOURCE_MEM)
  425. continue;
  426. lo = iova_pfn(iovad, window->res->start - window->offset);
  427. hi = iova_pfn(iovad, window->res->end - window->offset);
  428. reserve_iova(iovad, lo, hi);
  429. }
  430. /* Get reserved DMA windows from host bridge */
  431. list_sort(NULL, &bridge->dma_ranges, iommu_dma_ranges_sort);
  432. resource_list_for_each_entry(window, &bridge->dma_ranges) {
  433. end = window->res->start - window->offset;
  434. resv_iova:
  435. if (end > start) {
  436. lo = iova_pfn(iovad, start);
  437. hi = iova_pfn(iovad, end);
  438. reserve_iova(iovad, lo, hi);
  439. } else if (end < start) {
  440. /* DMA ranges should be non-overlapping */
  441. dev_err(&dev->dev,
  442. "Failed to reserve IOVA [%pa-%pa]\n",
  443. &start, &end);
  444. return -EINVAL;
  445. }
  446. start = window->res->end - window->offset + 1;
  447. /* If window is last entry */
  448. if (window->node.next == &bridge->dma_ranges &&
  449. end != ~(phys_addr_t)0) {
  450. end = ~(phys_addr_t)0;
  451. goto resv_iova;
  452. }
  453. }
  454. return 0;
  455. }
  456. static int iova_reserve_iommu_regions(struct device *dev,
  457. struct iommu_domain *domain)
  458. {
  459. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  460. struct iova_domain *iovad = &cookie->iovad;
  461. struct iommu_resv_region *region;
  462. LIST_HEAD(resv_regions);
  463. int ret = 0;
  464. if (dev_is_pci(dev)) {
  465. ret = iova_reserve_pci_windows(to_pci_dev(dev), iovad);
  466. if (ret)
  467. return ret;
  468. }
  469. iommu_get_resv_regions(dev, &resv_regions);
  470. list_for_each_entry(region, &resv_regions, list) {
  471. unsigned long lo, hi;
  472. /* We ARE the software that manages these! */
  473. if (region->type == IOMMU_RESV_SW_MSI)
  474. continue;
  475. lo = iova_pfn(iovad, region->start);
  476. hi = iova_pfn(iovad, region->start + region->length - 1);
  477. reserve_iova(iovad, lo, hi);
  478. if (region->type == IOMMU_RESV_MSI)
  479. ret = cookie_init_hw_msi_region(cookie, region->start,
  480. region->start + region->length);
  481. if (ret)
  482. break;
  483. }
  484. iommu_put_resv_regions(dev, &resv_regions);
  485. return ret;
  486. }
  487. static bool dev_is_untrusted(struct device *dev)
  488. {
  489. return dev_is_pci(dev) && to_pci_dev(dev)->untrusted;
  490. }
  491. static bool dev_use_swiotlb(struct device *dev, size_t size,
  492. enum dma_data_direction dir)
  493. {
  494. return IS_ENABLED(CONFIG_SWIOTLB) &&
  495. (dev_is_untrusted(dev) ||
  496. dma_kmalloc_needs_bounce(dev, size, dir));
  497. }
  498. static bool dev_use_sg_swiotlb(struct device *dev, struct scatterlist *sg,
  499. int nents, enum dma_data_direction dir)
  500. {
  501. struct scatterlist *s;
  502. int i;
  503. if (!IS_ENABLED(CONFIG_SWIOTLB))
  504. return false;
  505. if (dev_is_untrusted(dev))
  506. return true;
  507. /*
  508. * If kmalloc() buffers are not DMA-safe for this device and
  509. * direction, check the individual lengths in the sg list. If any
  510. * element is deemed unsafe, use the swiotlb for bouncing.
  511. */
  512. if (!dma_kmalloc_safe(dev, dir)) {
  513. for_each_sg(sg, s, nents, i)
  514. if (!dma_kmalloc_size_aligned(s->length))
  515. return true;
  516. }
  517. return false;
  518. }
  519. /**
  520. * iommu_dma_init_options - Initialize dma-iommu options
  521. * @options: The options to be initialized
  522. * @dev: Device the options are set for
  523. *
  524. * This allows tuning dma-iommu specific to device properties
  525. */
  526. static void iommu_dma_init_options(struct iommu_dma_options *options,
  527. struct device *dev)
  528. {
  529. /* Shadowing IOTLB flushes do better with a single large queue */
  530. if (dev->iommu->shadow_on_flush) {
  531. options->qt = IOMMU_DMA_OPTS_SINGLE_QUEUE;
  532. options->fq_timeout = IOVA_SINGLE_FQ_TIMEOUT;
  533. options->fq_size = IOVA_SINGLE_FQ_SIZE;
  534. } else {
  535. options->qt = IOMMU_DMA_OPTS_PER_CPU_QUEUE;
  536. options->fq_size = IOVA_DEFAULT_FQ_SIZE;
  537. options->fq_timeout = IOVA_DEFAULT_FQ_TIMEOUT;
  538. }
  539. }
  540. /**
  541. * iommu_dma_init_domain - Initialise a DMA mapping domain
  542. * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie()
  543. * @dev: Device the domain is being initialised for
  544. *
  545. * If the geometry and dma_range_map include address 0, we reserve that page
  546. * to ensure it is an invalid IOVA. It is safe to reinitialise a domain, but
  547. * any change which could make prior IOVAs invalid will fail.
  548. */
  549. static int iommu_dma_init_domain(struct iommu_domain *domain, struct device *dev)
  550. {
  551. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  552. const struct bus_dma_region *map = dev->dma_range_map;
  553. unsigned long order, base_pfn;
  554. struct iova_domain *iovad;
  555. int ret;
  556. if (!cookie || domain->cookie_type != IOMMU_COOKIE_DMA_IOVA)
  557. return -EINVAL;
  558. iovad = &cookie->iovad;
  559. /* Use the smallest supported page size for IOVA granularity */
  560. order = __ffs(domain->pgsize_bitmap);
  561. base_pfn = 1;
  562. /* Check the domain allows at least some access to the device... */
  563. if (map) {
  564. if (dma_range_map_min(map) > domain->geometry.aperture_end ||
  565. dma_range_map_max(map) < domain->geometry.aperture_start) {
  566. pr_warn("specified DMA range outside IOMMU capability\n");
  567. return -EFAULT;
  568. }
  569. }
  570. /* ...then finally give it a kicking to make sure it fits */
  571. base_pfn = max_t(unsigned long, base_pfn,
  572. domain->geometry.aperture_start >> order);
  573. /* start_pfn is always nonzero for an already-initialised domain */
  574. if (iovad->start_pfn) {
  575. if (1UL << order != iovad->granule ||
  576. base_pfn != iovad->start_pfn) {
  577. pr_warn("Incompatible range for DMA domain\n");
  578. return -EFAULT;
  579. }
  580. return 0;
  581. }
  582. init_iova_domain(iovad, 1UL << order, base_pfn);
  583. ret = iova_domain_init_rcaches(iovad);
  584. if (ret)
  585. return ret;
  586. iommu_dma_init_options(&cookie->options, dev);
  587. /* If the FQ fails we can simply fall back to strict mode */
  588. if (domain->type == IOMMU_DOMAIN_DMA_FQ &&
  589. (!device_iommu_capable(dev, IOMMU_CAP_DEFERRED_FLUSH) || iommu_dma_init_fq(domain)))
  590. domain->type = IOMMU_DOMAIN_DMA;
  591. return iova_reserve_iommu_regions(dev, domain);
  592. }
  593. /**
  594. * dma_info_to_prot - Translate DMA API directions and attributes to IOMMU API
  595. * page flags.
  596. * @dir: Direction of DMA transfer
  597. * @coherent: Is the DMA master cache-coherent?
  598. * @attrs: DMA attributes for the mapping
  599. *
  600. * Return: corresponding IOMMU API page protection flags
  601. */
  602. static int dma_info_to_prot(enum dma_data_direction dir, bool coherent,
  603. unsigned long attrs)
  604. {
  605. int prot;
  606. if (attrs & DMA_ATTR_MMIO)
  607. prot = IOMMU_MMIO;
  608. else
  609. prot = coherent ? IOMMU_CACHE : 0;
  610. if (attrs & DMA_ATTR_PRIVILEGED)
  611. prot |= IOMMU_PRIV;
  612. switch (dir) {
  613. case DMA_BIDIRECTIONAL:
  614. return prot | IOMMU_READ | IOMMU_WRITE;
  615. case DMA_TO_DEVICE:
  616. return prot | IOMMU_READ;
  617. case DMA_FROM_DEVICE:
  618. return prot | IOMMU_WRITE;
  619. default:
  620. return 0;
  621. }
  622. }
  623. static dma_addr_t iommu_dma_alloc_iova(struct iommu_domain *domain,
  624. size_t size, u64 dma_limit, struct device *dev)
  625. {
  626. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  627. struct iova_domain *iovad = &cookie->iovad;
  628. unsigned long shift, iova_len, iova;
  629. if (domain->cookie_type == IOMMU_COOKIE_DMA_MSI) {
  630. domain->msi_cookie->msi_iova += size;
  631. return domain->msi_cookie->msi_iova - size;
  632. }
  633. shift = iova_shift(iovad);
  634. iova_len = size >> shift;
  635. dma_limit = min_not_zero(dma_limit, dev->bus_dma_limit);
  636. if (domain->geometry.force_aperture)
  637. dma_limit = min(dma_limit, (u64)domain->geometry.aperture_end);
  638. /*
  639. * Try to use all the 32-bit PCI addresses first. The original SAC vs.
  640. * DAC reasoning loses relevance with PCIe, but enough hardware and
  641. * firmware bugs are still lurking out there that it's safest not to
  642. * venture into the 64-bit space until necessary.
  643. *
  644. * If your device goes wrong after seeing the notice then likely either
  645. * its driver is not setting DMA masks accurately, the hardware has
  646. * some inherent bug in handling >32-bit addresses, or not all the
  647. * expected address bits are wired up between the device and the IOMMU.
  648. */
  649. if (dma_limit > DMA_BIT_MASK(32) && dev->iommu->pci_32bit_workaround) {
  650. iova = alloc_iova_fast(iovad, iova_len,
  651. DMA_BIT_MASK(32) >> shift, false);
  652. if (iova)
  653. goto done;
  654. dev->iommu->pci_32bit_workaround = false;
  655. dev_notice(dev, "Using %d-bit DMA addresses\n", bits_per(dma_limit));
  656. }
  657. iova = alloc_iova_fast(iovad, iova_len, dma_limit >> shift, true);
  658. done:
  659. return (dma_addr_t)iova << shift;
  660. }
  661. static void iommu_dma_free_iova(struct iommu_domain *domain, dma_addr_t iova,
  662. size_t size, struct iommu_iotlb_gather *gather)
  663. {
  664. struct iova_domain *iovad = &domain->iova_cookie->iovad;
  665. /* The MSI case is only ever cleaning up its most recent allocation */
  666. if (domain->cookie_type == IOMMU_COOKIE_DMA_MSI)
  667. domain->msi_cookie->msi_iova -= size;
  668. else if (gather && gather->queued)
  669. queue_iova(domain->iova_cookie, iova_pfn(iovad, iova),
  670. size >> iova_shift(iovad),
  671. &gather->freelist);
  672. else
  673. free_iova_fast(iovad, iova_pfn(iovad, iova),
  674. size >> iova_shift(iovad));
  675. }
  676. static void __iommu_dma_unmap(struct device *dev, dma_addr_t dma_addr,
  677. size_t size)
  678. {
  679. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  680. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  681. struct iova_domain *iovad = &cookie->iovad;
  682. size_t iova_off = iova_offset(iovad, dma_addr);
  683. struct iommu_iotlb_gather iotlb_gather;
  684. size_t unmapped;
  685. dma_addr -= iova_off;
  686. size = iova_align(iovad, size + iova_off);
  687. iommu_iotlb_gather_init(&iotlb_gather);
  688. iotlb_gather.queued = READ_ONCE(cookie->fq_domain);
  689. unmapped = iommu_unmap_fast(domain, dma_addr, size, &iotlb_gather);
  690. WARN_ON(unmapped != size);
  691. if (!iotlb_gather.queued)
  692. iommu_iotlb_sync(domain, &iotlb_gather);
  693. iommu_dma_free_iova(domain, dma_addr, size, &iotlb_gather);
  694. }
  695. static dma_addr_t __iommu_dma_map(struct device *dev, phys_addr_t phys,
  696. size_t size, int prot, u64 dma_mask)
  697. {
  698. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  699. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  700. struct iova_domain *iovad = &cookie->iovad;
  701. size_t iova_off = iova_offset(iovad, phys);
  702. dma_addr_t iova;
  703. if (static_branch_unlikely(&iommu_deferred_attach_enabled) &&
  704. iommu_deferred_attach(dev, domain))
  705. return DMA_MAPPING_ERROR;
  706. /* If anyone ever wants this we'd need support in the IOVA allocator */
  707. if (dev_WARN_ONCE(dev, dma_get_min_align_mask(dev) > iova_mask(iovad),
  708. "Unsupported alignment constraint\n"))
  709. return DMA_MAPPING_ERROR;
  710. size = iova_align(iovad, size + iova_off);
  711. iova = iommu_dma_alloc_iova(domain, size, dma_mask, dev);
  712. if (!iova)
  713. return DMA_MAPPING_ERROR;
  714. if (iommu_map(domain, iova, phys - iova_off, size, prot, GFP_ATOMIC)) {
  715. iommu_dma_free_iova(domain, iova, size, NULL);
  716. return DMA_MAPPING_ERROR;
  717. }
  718. return iova + iova_off;
  719. }
  720. static void __iommu_dma_free_pages(struct page **pages, int count)
  721. {
  722. while (count--)
  723. __free_page(pages[count]);
  724. kvfree(pages);
  725. }
  726. static struct page **__iommu_dma_alloc_pages(struct device *dev,
  727. unsigned int count, unsigned long order_mask, gfp_t gfp)
  728. {
  729. struct page **pages;
  730. unsigned int i = 0, nid = dev_to_node(dev);
  731. order_mask &= GENMASK(MAX_PAGE_ORDER, 0);
  732. if (!order_mask)
  733. return NULL;
  734. pages = kvzalloc_objs(*pages, count);
  735. if (!pages)
  736. return NULL;
  737. /* IOMMU can map any pages, so himem can also be used here */
  738. gfp |= __GFP_NOWARN | __GFP_HIGHMEM;
  739. while (count) {
  740. struct page *page = NULL;
  741. unsigned int order_size;
  742. /*
  743. * Higher-order allocations are a convenience rather
  744. * than a necessity, hence using __GFP_NORETRY until
  745. * falling back to minimum-order allocations.
  746. */
  747. for (order_mask &= GENMASK(__fls(count), 0);
  748. order_mask; order_mask &= ~order_size) {
  749. unsigned int order = __fls(order_mask);
  750. gfp_t alloc_flags = gfp;
  751. order_size = 1U << order;
  752. if (order_mask > order_size)
  753. alloc_flags |= __GFP_NORETRY;
  754. page = alloc_pages_node(nid, alloc_flags, order);
  755. if (!page)
  756. continue;
  757. if (order)
  758. split_page(page, order);
  759. break;
  760. }
  761. if (!page) {
  762. __iommu_dma_free_pages(pages, i);
  763. return NULL;
  764. }
  765. count -= order_size;
  766. while (order_size--)
  767. pages[i++] = page++;
  768. }
  769. return pages;
  770. }
  771. /*
  772. * If size is less than PAGE_SIZE, then a full CPU page will be allocated,
  773. * but an IOMMU which supports smaller pages might not map the whole thing.
  774. */
  775. static struct page **__iommu_dma_alloc_noncontiguous(struct device *dev,
  776. size_t size, struct sg_table *sgt, gfp_t gfp, unsigned long attrs)
  777. {
  778. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  779. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  780. struct iova_domain *iovad = &cookie->iovad;
  781. bool coherent = dev_is_dma_coherent(dev);
  782. int ioprot = dma_info_to_prot(DMA_BIDIRECTIONAL, coherent, attrs);
  783. unsigned int count, min_size, alloc_sizes = domain->pgsize_bitmap;
  784. struct page **pages;
  785. dma_addr_t iova;
  786. ssize_t ret;
  787. if (static_branch_unlikely(&iommu_deferred_attach_enabled) &&
  788. iommu_deferred_attach(dev, domain))
  789. return NULL;
  790. min_size = alloc_sizes & -alloc_sizes;
  791. if (min_size < PAGE_SIZE) {
  792. min_size = PAGE_SIZE;
  793. alloc_sizes |= PAGE_SIZE;
  794. } else {
  795. size = ALIGN(size, min_size);
  796. }
  797. if (attrs & DMA_ATTR_ALLOC_SINGLE_PAGES)
  798. alloc_sizes = min_size;
  799. count = PAGE_ALIGN(size) >> PAGE_SHIFT;
  800. pages = __iommu_dma_alloc_pages(dev, count, alloc_sizes >> PAGE_SHIFT,
  801. gfp);
  802. if (!pages)
  803. return NULL;
  804. size = iova_align(iovad, size);
  805. iova = iommu_dma_alloc_iova(domain, size, dev->coherent_dma_mask, dev);
  806. if (!iova)
  807. goto out_free_pages;
  808. /*
  809. * Remove the zone/policy flags from the GFP - these are applied to the
  810. * __iommu_dma_alloc_pages() but are not used for the supporting
  811. * internal allocations that follow.
  812. */
  813. gfp &= ~(__GFP_DMA | __GFP_DMA32 | __GFP_HIGHMEM | __GFP_COMP);
  814. if (sg_alloc_table_from_pages(sgt, pages, count, 0, size, gfp))
  815. goto out_free_iova;
  816. if (!(ioprot & IOMMU_CACHE)) {
  817. struct scatterlist *sg;
  818. int i;
  819. for_each_sg(sgt->sgl, sg, sgt->orig_nents, i)
  820. arch_dma_prep_coherent(sg_page(sg), sg->length);
  821. }
  822. ret = iommu_map_sg(domain, iova, sgt->sgl, sgt->orig_nents, ioprot,
  823. gfp);
  824. if (ret < 0 || ret < size)
  825. goto out_free_sg;
  826. sgt->sgl->dma_address = iova;
  827. sgt->sgl->dma_length = size;
  828. return pages;
  829. out_free_sg:
  830. sg_free_table(sgt);
  831. out_free_iova:
  832. iommu_dma_free_iova(domain, iova, size, NULL);
  833. out_free_pages:
  834. __iommu_dma_free_pages(pages, count);
  835. return NULL;
  836. }
  837. static void *iommu_dma_alloc_remap(struct device *dev, size_t size,
  838. dma_addr_t *dma_handle, gfp_t gfp, unsigned long attrs)
  839. {
  840. struct page **pages;
  841. struct sg_table sgt;
  842. void *vaddr;
  843. pgprot_t prot = dma_pgprot(dev, PAGE_KERNEL, attrs);
  844. pages = __iommu_dma_alloc_noncontiguous(dev, size, &sgt, gfp, attrs);
  845. if (!pages)
  846. return NULL;
  847. *dma_handle = sgt.sgl->dma_address;
  848. sg_free_table(&sgt);
  849. vaddr = dma_common_pages_remap(pages, size, prot,
  850. __builtin_return_address(0));
  851. if (!vaddr)
  852. goto out_unmap;
  853. return vaddr;
  854. out_unmap:
  855. __iommu_dma_unmap(dev, *dma_handle, size);
  856. __iommu_dma_free_pages(pages, PAGE_ALIGN(size) >> PAGE_SHIFT);
  857. return NULL;
  858. }
  859. /*
  860. * This is the actual return value from the iommu_dma_alloc_noncontiguous.
  861. *
  862. * The users of the DMA API should only care about the sg_table, but to make
  863. * the DMA-API internal vmaping and freeing easier we stash away the page
  864. * array as well (except for the fallback case). This can go away any time,
  865. * e.g. when a vmap-variant that takes a scatterlist comes along.
  866. */
  867. struct dma_sgt_handle {
  868. struct sg_table sgt;
  869. struct page **pages;
  870. };
  871. #define sgt_handle(sgt) \
  872. container_of((sgt), struct dma_sgt_handle, sgt)
  873. struct sg_table *iommu_dma_alloc_noncontiguous(struct device *dev, size_t size,
  874. enum dma_data_direction dir, gfp_t gfp, unsigned long attrs)
  875. {
  876. struct dma_sgt_handle *sh;
  877. sh = kmalloc_obj(*sh, gfp);
  878. if (!sh)
  879. return NULL;
  880. sh->pages = __iommu_dma_alloc_noncontiguous(dev, size, &sh->sgt, gfp, attrs);
  881. if (!sh->pages) {
  882. kfree(sh);
  883. return NULL;
  884. }
  885. return &sh->sgt;
  886. }
  887. void iommu_dma_free_noncontiguous(struct device *dev, size_t size,
  888. struct sg_table *sgt, enum dma_data_direction dir)
  889. {
  890. struct dma_sgt_handle *sh = sgt_handle(sgt);
  891. __iommu_dma_unmap(dev, sgt->sgl->dma_address, size);
  892. __iommu_dma_free_pages(sh->pages, PAGE_ALIGN(size) >> PAGE_SHIFT);
  893. sg_free_table(&sh->sgt);
  894. kfree(sh);
  895. }
  896. void *iommu_dma_vmap_noncontiguous(struct device *dev, size_t size,
  897. struct sg_table *sgt)
  898. {
  899. unsigned long count = PAGE_ALIGN(size) >> PAGE_SHIFT;
  900. return vmap(sgt_handle(sgt)->pages, count, VM_MAP, PAGE_KERNEL);
  901. }
  902. int iommu_dma_mmap_noncontiguous(struct device *dev, struct vm_area_struct *vma,
  903. size_t size, struct sg_table *sgt)
  904. {
  905. unsigned long count = PAGE_ALIGN(size) >> PAGE_SHIFT;
  906. if (vma->vm_pgoff >= count || vma_pages(vma) > count - vma->vm_pgoff)
  907. return -ENXIO;
  908. return vm_map_pages(vma, sgt_handle(sgt)->pages, count);
  909. }
  910. void iommu_dma_sync_single_for_cpu(struct device *dev, dma_addr_t dma_handle,
  911. size_t size, enum dma_data_direction dir)
  912. {
  913. phys_addr_t phys;
  914. if (dev_is_dma_coherent(dev) && !dev_use_swiotlb(dev, size, dir))
  915. return;
  916. phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle);
  917. if (!dev_is_dma_coherent(dev))
  918. arch_sync_dma_for_cpu(phys, size, dir);
  919. swiotlb_sync_single_for_cpu(dev, phys, size, dir);
  920. }
  921. void iommu_dma_sync_single_for_device(struct device *dev, dma_addr_t dma_handle,
  922. size_t size, enum dma_data_direction dir)
  923. {
  924. phys_addr_t phys;
  925. if (dev_is_dma_coherent(dev) && !dev_use_swiotlb(dev, size, dir))
  926. return;
  927. phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle);
  928. swiotlb_sync_single_for_device(dev, phys, size, dir);
  929. if (!dev_is_dma_coherent(dev))
  930. arch_sync_dma_for_device(phys, size, dir);
  931. }
  932. void iommu_dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sgl,
  933. int nelems, enum dma_data_direction dir)
  934. {
  935. struct scatterlist *sg;
  936. int i;
  937. if (sg_dma_is_swiotlb(sgl))
  938. for_each_sg(sgl, sg, nelems, i)
  939. iommu_dma_sync_single_for_cpu(dev, sg_dma_address(sg),
  940. sg->length, dir);
  941. else if (!dev_is_dma_coherent(dev))
  942. for_each_sg(sgl, sg, nelems, i)
  943. arch_sync_dma_for_cpu(sg_phys(sg), sg->length, dir);
  944. }
  945. void iommu_dma_sync_sg_for_device(struct device *dev, struct scatterlist *sgl,
  946. int nelems, enum dma_data_direction dir)
  947. {
  948. struct scatterlist *sg;
  949. int i;
  950. if (sg_dma_is_swiotlb(sgl))
  951. for_each_sg(sgl, sg, nelems, i)
  952. iommu_dma_sync_single_for_device(dev,
  953. sg_dma_address(sg),
  954. sg->length, dir);
  955. else if (!dev_is_dma_coherent(dev))
  956. for_each_sg(sgl, sg, nelems, i)
  957. arch_sync_dma_for_device(sg_phys(sg), sg->length, dir);
  958. }
  959. static phys_addr_t iommu_dma_map_swiotlb(struct device *dev, phys_addr_t phys,
  960. size_t size, enum dma_data_direction dir, unsigned long attrs)
  961. {
  962. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  963. struct iova_domain *iovad = &domain->iova_cookie->iovad;
  964. if (!is_swiotlb_active(dev)) {
  965. dev_warn_once(dev, "DMA bounce buffers are inactive, unable to map unaligned transaction.\n");
  966. return (phys_addr_t)DMA_MAPPING_ERROR;
  967. }
  968. trace_swiotlb_bounced(dev, phys, size);
  969. phys = swiotlb_tbl_map_single(dev, phys, size, iova_mask(iovad), dir,
  970. attrs);
  971. /*
  972. * Untrusted devices should not see padding areas with random leftover
  973. * kernel data, so zero the pre- and post-padding.
  974. * swiotlb_tbl_map_single() has initialized the bounce buffer proper to
  975. * the contents of the original memory buffer.
  976. */
  977. if (phys != (phys_addr_t)DMA_MAPPING_ERROR && dev_is_untrusted(dev)) {
  978. size_t start, virt = (size_t)phys_to_virt(phys);
  979. /* Pre-padding */
  980. start = iova_align_down(iovad, virt);
  981. memset((void *)start, 0, virt - start);
  982. /* Post-padding */
  983. start = virt + size;
  984. memset((void *)start, 0, iova_align(iovad, start) - start);
  985. }
  986. return phys;
  987. }
  988. /*
  989. * Checks if a physical buffer has unaligned boundaries with respect to
  990. * the IOMMU granule. Returns non-zero if either the start or end
  991. * address is not aligned to the granule boundary.
  992. */
  993. static inline size_t iova_unaligned(struct iova_domain *iovad, phys_addr_t phys,
  994. size_t size)
  995. {
  996. return iova_offset(iovad, phys | size);
  997. }
  998. dma_addr_t iommu_dma_map_phys(struct device *dev, phys_addr_t phys, size_t size,
  999. enum dma_data_direction dir, unsigned long attrs)
  1000. {
  1001. bool coherent = dev_is_dma_coherent(dev);
  1002. int prot = dma_info_to_prot(dir, coherent, attrs);
  1003. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  1004. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  1005. struct iova_domain *iovad = &cookie->iovad;
  1006. dma_addr_t iova, dma_mask = dma_get_mask(dev);
  1007. /*
  1008. * If both the physical buffer start address and size are page aligned,
  1009. * we don't need to use a bounce page.
  1010. */
  1011. if (dev_use_swiotlb(dev, size, dir) &&
  1012. iova_unaligned(iovad, phys, size)) {
  1013. if (attrs & (DMA_ATTR_MMIO | DMA_ATTR_REQUIRE_COHERENT))
  1014. return DMA_MAPPING_ERROR;
  1015. phys = iommu_dma_map_swiotlb(dev, phys, size, dir, attrs);
  1016. if (phys == (phys_addr_t)DMA_MAPPING_ERROR)
  1017. return DMA_MAPPING_ERROR;
  1018. }
  1019. if (!coherent && !(attrs & (DMA_ATTR_SKIP_CPU_SYNC | DMA_ATTR_MMIO)))
  1020. arch_sync_dma_for_device(phys, size, dir);
  1021. iova = __iommu_dma_map(dev, phys, size, prot, dma_mask);
  1022. if (iova == DMA_MAPPING_ERROR &&
  1023. !(attrs & (DMA_ATTR_MMIO | DMA_ATTR_REQUIRE_COHERENT)))
  1024. swiotlb_tbl_unmap_single(dev, phys, size, dir, attrs);
  1025. return iova;
  1026. }
  1027. void iommu_dma_unmap_phys(struct device *dev, dma_addr_t dma_handle,
  1028. size_t size, enum dma_data_direction dir, unsigned long attrs)
  1029. {
  1030. phys_addr_t phys;
  1031. if (attrs & (DMA_ATTR_MMIO | DMA_ATTR_REQUIRE_COHERENT)) {
  1032. __iommu_dma_unmap(dev, dma_handle, size);
  1033. return;
  1034. }
  1035. phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle);
  1036. if (WARN_ON(!phys))
  1037. return;
  1038. if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) && !dev_is_dma_coherent(dev))
  1039. arch_sync_dma_for_cpu(phys, size, dir);
  1040. __iommu_dma_unmap(dev, dma_handle, size);
  1041. swiotlb_tbl_unmap_single(dev, phys, size, dir, attrs);
  1042. }
  1043. /*
  1044. * Prepare a successfully-mapped scatterlist to give back to the caller.
  1045. *
  1046. * At this point the segments are already laid out by iommu_dma_map_sg() to
  1047. * avoid individually crossing any boundaries, so we merely need to check a
  1048. * segment's start address to avoid concatenating across one.
  1049. */
  1050. static int __finalise_sg(struct device *dev, struct scatterlist *sg, int nents,
  1051. dma_addr_t dma_addr)
  1052. {
  1053. struct scatterlist *s, *cur = sg;
  1054. unsigned long seg_mask = dma_get_seg_boundary(dev);
  1055. unsigned int cur_len = 0, max_len = dma_get_max_seg_size(dev);
  1056. int i, count = 0;
  1057. for_each_sg(sg, s, nents, i) {
  1058. /* Restore this segment's original unaligned fields first */
  1059. dma_addr_t s_dma_addr = sg_dma_address(s);
  1060. unsigned int s_iova_off = sg_dma_address(s);
  1061. unsigned int s_length = sg_dma_len(s);
  1062. unsigned int s_iova_len = s->length;
  1063. sg_dma_address(s) = DMA_MAPPING_ERROR;
  1064. sg_dma_len(s) = 0;
  1065. if (sg_dma_is_bus_address(s)) {
  1066. if (i > 0)
  1067. cur = sg_next(cur);
  1068. sg_dma_unmark_bus_address(s);
  1069. sg_dma_address(cur) = s_dma_addr;
  1070. sg_dma_len(cur) = s_length;
  1071. sg_dma_mark_bus_address(cur);
  1072. count++;
  1073. cur_len = 0;
  1074. continue;
  1075. }
  1076. s->offset += s_iova_off;
  1077. s->length = s_length;
  1078. /*
  1079. * Now fill in the real DMA data. If...
  1080. * - there is a valid output segment to append to
  1081. * - and this segment starts on an IOVA page boundary
  1082. * - but doesn't fall at a segment boundary
  1083. * - and wouldn't make the resulting output segment too long
  1084. */
  1085. if (cur_len && !s_iova_off && (dma_addr & seg_mask) &&
  1086. (max_len - cur_len >= s_length)) {
  1087. /* ...then concatenate it with the previous one */
  1088. cur_len += s_length;
  1089. } else {
  1090. /* Otherwise start the next output segment */
  1091. if (i > 0)
  1092. cur = sg_next(cur);
  1093. cur_len = s_length;
  1094. count++;
  1095. sg_dma_address(cur) = dma_addr + s_iova_off;
  1096. }
  1097. sg_dma_len(cur) = cur_len;
  1098. dma_addr += s_iova_len;
  1099. if (s_length + s_iova_off < s_iova_len)
  1100. cur_len = 0;
  1101. }
  1102. return count;
  1103. }
  1104. /*
  1105. * If mapping failed, then just restore the original list,
  1106. * but making sure the DMA fields are invalidated.
  1107. */
  1108. static void __invalidate_sg(struct scatterlist *sg, int nents)
  1109. {
  1110. struct scatterlist *s;
  1111. int i;
  1112. for_each_sg(sg, s, nents, i) {
  1113. if (sg_dma_is_bus_address(s)) {
  1114. sg_dma_unmark_bus_address(s);
  1115. } else {
  1116. if (sg_dma_address(s) != DMA_MAPPING_ERROR)
  1117. s->offset += sg_dma_address(s);
  1118. if (sg_dma_len(s))
  1119. s->length = sg_dma_len(s);
  1120. }
  1121. sg_dma_address(s) = DMA_MAPPING_ERROR;
  1122. sg_dma_len(s) = 0;
  1123. }
  1124. }
  1125. static void iommu_dma_unmap_sg_swiotlb(struct device *dev, struct scatterlist *sg,
  1126. int nents, enum dma_data_direction dir, unsigned long attrs)
  1127. {
  1128. struct scatterlist *s;
  1129. int i;
  1130. for_each_sg(sg, s, nents, i)
  1131. iommu_dma_unmap_phys(dev, sg_dma_address(s),
  1132. sg_dma_len(s), dir, attrs);
  1133. }
  1134. static int iommu_dma_map_sg_swiotlb(struct device *dev, struct scatterlist *sg,
  1135. int nents, enum dma_data_direction dir, unsigned long attrs)
  1136. {
  1137. struct scatterlist *s;
  1138. int i;
  1139. sg_dma_mark_swiotlb(sg);
  1140. for_each_sg(sg, s, nents, i) {
  1141. sg_dma_address(s) = iommu_dma_map_phys(dev, sg_phys(s),
  1142. s->length, dir, attrs);
  1143. if (sg_dma_address(s) == DMA_MAPPING_ERROR)
  1144. goto out_unmap;
  1145. sg_dma_len(s) = s->length;
  1146. }
  1147. return nents;
  1148. out_unmap:
  1149. iommu_dma_unmap_sg_swiotlb(dev, sg, i, dir, attrs | DMA_ATTR_SKIP_CPU_SYNC);
  1150. return -EIO;
  1151. }
  1152. /*
  1153. * The DMA API client is passing in a scatterlist which could describe
  1154. * any old buffer layout, but the IOMMU API requires everything to be
  1155. * aligned to IOMMU pages. Hence the need for this complicated bit of
  1156. * impedance-matching, to be able to hand off a suitably-aligned list,
  1157. * but still preserve the original offsets and sizes for the caller.
  1158. */
  1159. int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
  1160. enum dma_data_direction dir, unsigned long attrs)
  1161. {
  1162. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  1163. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  1164. struct iova_domain *iovad = &cookie->iovad;
  1165. struct scatterlist *s, *prev = NULL;
  1166. int prot = dma_info_to_prot(dir, dev_is_dma_coherent(dev), attrs);
  1167. struct pci_p2pdma_map_state p2pdma_state = {};
  1168. dma_addr_t iova;
  1169. size_t iova_len = 0;
  1170. unsigned long mask = dma_get_seg_boundary(dev);
  1171. ssize_t ret;
  1172. int i;
  1173. if (static_branch_unlikely(&iommu_deferred_attach_enabled)) {
  1174. ret = iommu_deferred_attach(dev, domain);
  1175. if (ret)
  1176. goto out;
  1177. }
  1178. if (dev_use_sg_swiotlb(dev, sg, nents, dir))
  1179. return iommu_dma_map_sg_swiotlb(dev, sg, nents, dir, attrs);
  1180. if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
  1181. iommu_dma_sync_sg_for_device(dev, sg, nents, dir);
  1182. /*
  1183. * Work out how much IOVA space we need, and align the segments to
  1184. * IOVA granules for the IOMMU driver to handle. With some clever
  1185. * trickery we can modify the list in-place, but reversibly, by
  1186. * stashing the unaligned parts in the as-yet-unused DMA fields.
  1187. */
  1188. for_each_sg(sg, s, nents, i) {
  1189. size_t s_iova_off = iova_offset(iovad, s->offset);
  1190. size_t s_length = s->length;
  1191. size_t pad_len = (mask - iova_len + 1) & mask;
  1192. switch (pci_p2pdma_state(&p2pdma_state, dev, sg_page(s))) {
  1193. case PCI_P2PDMA_MAP_THRU_HOST_BRIDGE:
  1194. /*
  1195. * Mapping through host bridge should be mapped with
  1196. * regular IOVAs, thus we do nothing here and continue
  1197. * below.
  1198. */
  1199. break;
  1200. case PCI_P2PDMA_MAP_NONE:
  1201. break;
  1202. case PCI_P2PDMA_MAP_BUS_ADDR:
  1203. /*
  1204. * iommu_map_sg() will skip this segment as it is marked
  1205. * as a bus address, __finalise_sg() will copy the dma
  1206. * address into the output segment.
  1207. */
  1208. s->dma_address = pci_p2pdma_bus_addr_map(
  1209. p2pdma_state.mem, sg_phys(s));
  1210. sg_dma_len(s) = sg->length;
  1211. sg_dma_mark_bus_address(s);
  1212. continue;
  1213. default:
  1214. ret = -EREMOTEIO;
  1215. goto out_restore_sg;
  1216. }
  1217. sg_dma_address(s) = s_iova_off;
  1218. sg_dma_len(s) = s_length;
  1219. s->offset -= s_iova_off;
  1220. s_length = iova_align(iovad, s_length + s_iova_off);
  1221. s->length = s_length;
  1222. /*
  1223. * Due to the alignment of our single IOVA allocation, we can
  1224. * depend on these assumptions about the segment boundary mask:
  1225. * - If mask size >= IOVA size, then the IOVA range cannot
  1226. * possibly fall across a boundary, so we don't care.
  1227. * - If mask size < IOVA size, then the IOVA range must start
  1228. * exactly on a boundary, therefore we can lay things out
  1229. * based purely on segment lengths without needing to know
  1230. * the actual addresses beforehand.
  1231. * - The mask must be a power of 2, so pad_len == 0 if
  1232. * iova_len == 0, thus we cannot dereference prev the first
  1233. * time through here (i.e. before it has a meaningful value).
  1234. */
  1235. if (pad_len && pad_len < s_length - 1) {
  1236. prev->length += pad_len;
  1237. iova_len += pad_len;
  1238. }
  1239. iova_len += s_length;
  1240. prev = s;
  1241. }
  1242. if (!iova_len)
  1243. return __finalise_sg(dev, sg, nents, 0);
  1244. iova = iommu_dma_alloc_iova(domain, iova_len, dma_get_mask(dev), dev);
  1245. if (!iova) {
  1246. ret = -ENOMEM;
  1247. goto out_restore_sg;
  1248. }
  1249. /*
  1250. * We'll leave any physical concatenation to the IOMMU driver's
  1251. * implementation - it knows better than we do.
  1252. */
  1253. ret = iommu_map_sg(domain, iova, sg, nents, prot, GFP_ATOMIC);
  1254. if (ret < 0 || ret < iova_len)
  1255. goto out_free_iova;
  1256. return __finalise_sg(dev, sg, nents, iova);
  1257. out_free_iova:
  1258. iommu_dma_free_iova(domain, iova, iova_len, NULL);
  1259. out_restore_sg:
  1260. __invalidate_sg(sg, nents);
  1261. out:
  1262. if (ret != -ENOMEM && ret != -EREMOTEIO)
  1263. return -EINVAL;
  1264. return ret;
  1265. }
  1266. void iommu_dma_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
  1267. enum dma_data_direction dir, unsigned long attrs)
  1268. {
  1269. dma_addr_t end = 0, start;
  1270. struct scatterlist *tmp;
  1271. int i;
  1272. if (sg_dma_is_swiotlb(sg)) {
  1273. iommu_dma_unmap_sg_swiotlb(dev, sg, nents, dir, attrs);
  1274. return;
  1275. }
  1276. if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
  1277. iommu_dma_sync_sg_for_cpu(dev, sg, nents, dir);
  1278. /*
  1279. * The scatterlist segments are mapped into a single
  1280. * contiguous IOVA allocation, the start and end points
  1281. * just have to be determined.
  1282. */
  1283. for_each_sg(sg, tmp, nents, i) {
  1284. if (sg_dma_is_bus_address(tmp)) {
  1285. sg_dma_unmark_bus_address(tmp);
  1286. continue;
  1287. }
  1288. if (sg_dma_len(tmp) == 0)
  1289. break;
  1290. start = sg_dma_address(tmp);
  1291. break;
  1292. }
  1293. nents -= i;
  1294. for_each_sg(tmp, tmp, nents, i) {
  1295. if (sg_dma_is_bus_address(tmp)) {
  1296. sg_dma_unmark_bus_address(tmp);
  1297. continue;
  1298. }
  1299. if (sg_dma_len(tmp) == 0)
  1300. break;
  1301. end = sg_dma_address(tmp) + sg_dma_len(tmp);
  1302. }
  1303. if (end)
  1304. __iommu_dma_unmap(dev, start, end - start);
  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. /**
  1460. * dma_iova_try_alloc - Try to allocate an IOVA space
  1461. * @dev: Device to allocate the IOVA space for
  1462. * @state: IOVA state
  1463. * @phys: physical address
  1464. * @size: IOVA size
  1465. *
  1466. * Check if @dev supports the IOVA-based DMA API, and if yes allocate IOVA space
  1467. * for the given base address and size.
  1468. *
  1469. * Note: @phys is only used to calculate the IOVA alignment. Callers that always
  1470. * do PAGE_SIZE aligned transfers can safely pass 0 here.
  1471. *
  1472. * Returns %true if the IOVA-based DMA API can be used and IOVA space has been
  1473. * allocated, or %false if the regular DMA API should be used.
  1474. */
  1475. bool dma_iova_try_alloc(struct device *dev, struct dma_iova_state *state,
  1476. phys_addr_t phys, size_t size)
  1477. {
  1478. struct iommu_dma_cookie *cookie;
  1479. struct iommu_domain *domain;
  1480. struct iova_domain *iovad;
  1481. size_t iova_off;
  1482. dma_addr_t addr;
  1483. memset(state, 0, sizeof(*state));
  1484. if (!use_dma_iommu(dev))
  1485. return false;
  1486. domain = iommu_get_dma_domain(dev);
  1487. cookie = domain->iova_cookie;
  1488. iovad = &cookie->iovad;
  1489. iova_off = iova_offset(iovad, phys);
  1490. if (static_branch_unlikely(&iommu_deferred_attach_enabled) &&
  1491. iommu_deferred_attach(dev, iommu_get_domain_for_dev(dev)))
  1492. return false;
  1493. if (WARN_ON_ONCE(!size))
  1494. return false;
  1495. /*
  1496. * DMA_IOVA_USE_SWIOTLB is flag which is set by dma-iommu
  1497. * internals, make sure that caller didn't set it and/or
  1498. * didn't use this interface to map SIZE_MAX.
  1499. */
  1500. if (WARN_ON_ONCE((u64)size & DMA_IOVA_USE_SWIOTLB))
  1501. return false;
  1502. addr = iommu_dma_alloc_iova(domain,
  1503. iova_align(iovad, size + iova_off),
  1504. dma_get_mask(dev), dev);
  1505. if (!addr)
  1506. return false;
  1507. state->addr = addr + iova_off;
  1508. state->__size = size;
  1509. return true;
  1510. }
  1511. EXPORT_SYMBOL_GPL(dma_iova_try_alloc);
  1512. /**
  1513. * dma_iova_free - Free an IOVA space
  1514. * @dev: Device to free the IOVA space for
  1515. * @state: IOVA state
  1516. *
  1517. * Undoes a successful dma_try_iova_alloc().
  1518. *
  1519. * Note that all dma_iova_link() calls need to be undone first. For callers
  1520. * that never call dma_iova_unlink(), dma_iova_destroy() can be used instead
  1521. * which unlinks all ranges and frees the IOVA space in a single efficient
  1522. * operation.
  1523. */
  1524. void dma_iova_free(struct device *dev, struct dma_iova_state *state)
  1525. {
  1526. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  1527. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  1528. struct iova_domain *iovad = &cookie->iovad;
  1529. size_t iova_start_pad = iova_offset(iovad, state->addr);
  1530. size_t size = dma_iova_size(state);
  1531. iommu_dma_free_iova(domain, state->addr - iova_start_pad,
  1532. iova_align(iovad, size + iova_start_pad), NULL);
  1533. }
  1534. EXPORT_SYMBOL_GPL(dma_iova_free);
  1535. static int __dma_iova_link(struct device *dev, dma_addr_t addr,
  1536. phys_addr_t phys, size_t size, enum dma_data_direction dir,
  1537. unsigned long attrs)
  1538. {
  1539. bool coherent = dev_is_dma_coherent(dev);
  1540. int prot = dma_info_to_prot(dir, coherent, attrs);
  1541. if (!coherent && !(attrs & (DMA_ATTR_SKIP_CPU_SYNC | DMA_ATTR_MMIO)))
  1542. arch_sync_dma_for_device(phys, size, dir);
  1543. return iommu_map_nosync(iommu_get_dma_domain(dev), addr, phys, size,
  1544. prot, GFP_ATOMIC);
  1545. }
  1546. static int iommu_dma_iova_bounce_and_link(struct device *dev, dma_addr_t addr,
  1547. phys_addr_t phys, size_t bounce_len,
  1548. enum dma_data_direction dir, unsigned long attrs,
  1549. size_t iova_start_pad)
  1550. {
  1551. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  1552. struct iova_domain *iovad = &domain->iova_cookie->iovad;
  1553. phys_addr_t bounce_phys;
  1554. int error;
  1555. bounce_phys = iommu_dma_map_swiotlb(dev, phys, bounce_len, dir, attrs);
  1556. if (bounce_phys == DMA_MAPPING_ERROR)
  1557. return -ENOMEM;
  1558. error = __dma_iova_link(dev, addr - iova_start_pad,
  1559. bounce_phys - iova_start_pad,
  1560. iova_align(iovad, bounce_len), dir, attrs);
  1561. if (error)
  1562. swiotlb_tbl_unmap_single(dev, bounce_phys, bounce_len, dir,
  1563. attrs);
  1564. return error;
  1565. }
  1566. static int iommu_dma_iova_link_swiotlb(struct device *dev,
  1567. struct dma_iova_state *state, phys_addr_t phys, size_t offset,
  1568. size_t size, enum dma_data_direction dir, unsigned long attrs)
  1569. {
  1570. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  1571. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  1572. struct iova_domain *iovad = &cookie->iovad;
  1573. size_t iova_start_pad = iova_offset(iovad, phys);
  1574. size_t iova_end_pad = iova_offset(iovad, phys + size);
  1575. dma_addr_t addr = state->addr + offset;
  1576. size_t mapped = 0;
  1577. int error;
  1578. if (iova_start_pad) {
  1579. size_t bounce_len = min(size, iovad->granule - iova_start_pad);
  1580. error = iommu_dma_iova_bounce_and_link(dev, addr, phys,
  1581. bounce_len, dir, attrs, iova_start_pad);
  1582. if (error)
  1583. return error;
  1584. state->__size |= DMA_IOVA_USE_SWIOTLB;
  1585. mapped += bounce_len;
  1586. size -= bounce_len;
  1587. if (!size)
  1588. return 0;
  1589. }
  1590. size -= iova_end_pad;
  1591. error = __dma_iova_link(dev, addr + mapped, phys + mapped, size, dir,
  1592. attrs);
  1593. if (error)
  1594. goto out_unmap;
  1595. mapped += size;
  1596. if (iova_end_pad) {
  1597. error = iommu_dma_iova_bounce_and_link(dev, addr + mapped,
  1598. phys + mapped, iova_end_pad, dir, attrs, 0);
  1599. if (error)
  1600. goto out_unmap;
  1601. state->__size |= DMA_IOVA_USE_SWIOTLB;
  1602. }
  1603. return 0;
  1604. out_unmap:
  1605. dma_iova_unlink(dev, state, 0, mapped, dir, attrs);
  1606. return error;
  1607. }
  1608. /**
  1609. * dma_iova_link - Link a range of IOVA space
  1610. * @dev: DMA device
  1611. * @state: IOVA state
  1612. * @phys: physical address to link
  1613. * @offset: offset into the IOVA state to map into
  1614. * @size: size of the buffer
  1615. * @dir: DMA direction
  1616. * @attrs: attributes of mapping properties
  1617. *
  1618. * Link a range of IOVA space for the given IOVA state without IOTLB sync.
  1619. * This function is used to link multiple physical addresses in contiguous
  1620. * IOVA space without performing costly IOTLB sync.
  1621. *
  1622. * The caller is responsible to call to dma_iova_sync() to sync IOTLB at
  1623. * the end of linkage.
  1624. */
  1625. int dma_iova_link(struct device *dev, struct dma_iova_state *state,
  1626. phys_addr_t phys, size_t offset, size_t size,
  1627. enum dma_data_direction dir, unsigned long attrs)
  1628. {
  1629. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  1630. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  1631. struct iova_domain *iovad = &cookie->iovad;
  1632. size_t iova_start_pad = iova_offset(iovad, phys);
  1633. if (WARN_ON_ONCE(iova_start_pad && offset > 0))
  1634. return -EIO;
  1635. /*
  1636. * DMA_IOVA_USE_SWIOTLB is set on state after some entry
  1637. * took SWIOTLB path, which we were supposed to prevent
  1638. * for DMA_ATTR_REQUIRE_COHERENT attribute.
  1639. */
  1640. if (WARN_ON_ONCE((state->__size & DMA_IOVA_USE_SWIOTLB) &&
  1641. (attrs & DMA_ATTR_REQUIRE_COHERENT)))
  1642. return -EOPNOTSUPP;
  1643. if (!dev_is_dma_coherent(dev) && (attrs & DMA_ATTR_REQUIRE_COHERENT))
  1644. return -EOPNOTSUPP;
  1645. if (dev_use_swiotlb(dev, size, dir) &&
  1646. iova_unaligned(iovad, phys, size)) {
  1647. if (attrs & (DMA_ATTR_MMIO | DMA_ATTR_REQUIRE_COHERENT))
  1648. return -EPERM;
  1649. return iommu_dma_iova_link_swiotlb(dev, state, phys, offset,
  1650. size, dir, attrs);
  1651. }
  1652. return __dma_iova_link(dev, state->addr + offset - iova_start_pad,
  1653. phys - iova_start_pad,
  1654. iova_align(iovad, size + iova_start_pad), dir, attrs);
  1655. }
  1656. EXPORT_SYMBOL_GPL(dma_iova_link);
  1657. /**
  1658. * dma_iova_sync - Sync IOTLB
  1659. * @dev: DMA device
  1660. * @state: IOVA state
  1661. * @offset: offset into the IOVA state to sync
  1662. * @size: size of the buffer
  1663. *
  1664. * Sync IOTLB for the given IOVA state. This function should be called on
  1665. * the IOVA-contiguous range created by one ore more dma_iova_link() calls
  1666. * to sync the IOTLB.
  1667. */
  1668. int dma_iova_sync(struct device *dev, struct dma_iova_state *state,
  1669. size_t offset, size_t size)
  1670. {
  1671. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  1672. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  1673. struct iova_domain *iovad = &cookie->iovad;
  1674. dma_addr_t addr = state->addr + offset;
  1675. size_t iova_start_pad = iova_offset(iovad, addr);
  1676. return iommu_sync_map(domain, addr - iova_start_pad,
  1677. iova_align(iovad, size + iova_start_pad));
  1678. }
  1679. EXPORT_SYMBOL_GPL(dma_iova_sync);
  1680. static void iommu_dma_iova_unlink_range_slow(struct device *dev,
  1681. dma_addr_t addr, size_t size, enum dma_data_direction dir,
  1682. unsigned long attrs)
  1683. {
  1684. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  1685. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  1686. struct iova_domain *iovad = &cookie->iovad;
  1687. size_t iova_start_pad = iova_offset(iovad, addr);
  1688. dma_addr_t end = addr + size;
  1689. do {
  1690. phys_addr_t phys;
  1691. size_t len;
  1692. phys = iommu_iova_to_phys(domain, addr);
  1693. if (WARN_ON(!phys))
  1694. /* Something very horrible happen here */
  1695. return;
  1696. len = min_t(size_t,
  1697. end - addr, iovad->granule - iova_start_pad);
  1698. if (!dev_is_dma_coherent(dev) &&
  1699. !(attrs & (DMA_ATTR_SKIP_CPU_SYNC | DMA_ATTR_MMIO)))
  1700. arch_sync_dma_for_cpu(phys, len, dir);
  1701. swiotlb_tbl_unmap_single(dev, phys, len, dir, attrs);
  1702. addr += len;
  1703. iova_start_pad = 0;
  1704. } while (addr < end);
  1705. }
  1706. static void __iommu_dma_iova_unlink(struct device *dev,
  1707. struct dma_iova_state *state, size_t offset, size_t size,
  1708. enum dma_data_direction dir, unsigned long attrs,
  1709. bool free_iova)
  1710. {
  1711. struct iommu_domain *domain = iommu_get_dma_domain(dev);
  1712. struct iommu_dma_cookie *cookie = domain->iova_cookie;
  1713. struct iova_domain *iovad = &cookie->iovad;
  1714. dma_addr_t addr = state->addr + offset;
  1715. size_t iova_start_pad = iova_offset(iovad, addr);
  1716. struct iommu_iotlb_gather iotlb_gather;
  1717. size_t unmapped;
  1718. if ((state->__size & DMA_IOVA_USE_SWIOTLB) ||
  1719. (!dev_is_dma_coherent(dev) &&
  1720. !(attrs & (DMA_ATTR_SKIP_CPU_SYNC | DMA_ATTR_MMIO))))
  1721. iommu_dma_iova_unlink_range_slow(dev, addr, size, dir, attrs);
  1722. iommu_iotlb_gather_init(&iotlb_gather);
  1723. iotlb_gather.queued = free_iova && READ_ONCE(cookie->fq_domain);
  1724. size = iova_align(iovad, size + iova_start_pad);
  1725. addr -= iova_start_pad;
  1726. unmapped = iommu_unmap_fast(domain, addr, size, &iotlb_gather);
  1727. WARN_ON(unmapped != size);
  1728. if (!iotlb_gather.queued)
  1729. iommu_iotlb_sync(domain, &iotlb_gather);
  1730. if (free_iova)
  1731. iommu_dma_free_iova(domain, addr, size, &iotlb_gather);
  1732. }
  1733. /**
  1734. * dma_iova_unlink - Unlink a range of IOVA space
  1735. * @dev: DMA device
  1736. * @state: IOVA state
  1737. * @offset: offset into the IOVA state to unlink
  1738. * @size: size of the buffer
  1739. * @dir: DMA direction
  1740. * @attrs: attributes of mapping properties
  1741. *
  1742. * Unlink a range of IOVA space for the given IOVA state.
  1743. */
  1744. void dma_iova_unlink(struct device *dev, struct dma_iova_state *state,
  1745. size_t offset, size_t size, enum dma_data_direction dir,
  1746. unsigned long attrs)
  1747. {
  1748. __iommu_dma_iova_unlink(dev, state, offset, size, dir, attrs, false);
  1749. }
  1750. EXPORT_SYMBOL_GPL(dma_iova_unlink);
  1751. /**
  1752. * dma_iova_destroy - Finish a DMA mapping transaction
  1753. * @dev: DMA device
  1754. * @state: IOVA state
  1755. * @mapped_len: number of bytes to unmap
  1756. * @dir: DMA direction
  1757. * @attrs: attributes of mapping properties
  1758. *
  1759. * Unlink the IOVA range up to @mapped_len and free the entire IOVA space. The
  1760. * range of IOVA from dma_addr to @mapped_len must all be linked, and be the
  1761. * only linked IOVA in state.
  1762. */
  1763. void dma_iova_destroy(struct device *dev, struct dma_iova_state *state,
  1764. size_t mapped_len, enum dma_data_direction dir,
  1765. unsigned long attrs)
  1766. {
  1767. if (mapped_len)
  1768. __iommu_dma_iova_unlink(dev, state, 0, mapped_len, dir, attrs,
  1769. true);
  1770. else
  1771. /*
  1772. * We can be here if first call to dma_iova_link() failed and
  1773. * there is nothing to unlink, so let's be more clear.
  1774. */
  1775. dma_iova_free(dev, state);
  1776. }
  1777. EXPORT_SYMBOL_GPL(dma_iova_destroy);
  1778. void iommu_setup_dma_ops(struct device *dev, struct iommu_domain *domain)
  1779. {
  1780. if (dev_is_pci(dev))
  1781. dev->iommu->pci_32bit_workaround = !iommu_dma_forcedac;
  1782. dev->dma_iommu = iommu_is_dma_domain(domain);
  1783. if (dev->dma_iommu && iommu_dma_init_domain(domain, dev))
  1784. goto out_err;
  1785. return;
  1786. out_err:
  1787. pr_warn("Failed to set up IOMMU for device %s; retaining platform DMA ops\n",
  1788. dev_name(dev));
  1789. dev->dma_iommu = false;
  1790. }
  1791. static bool has_msi_cookie(const struct iommu_domain *domain)
  1792. {
  1793. return domain && (domain->cookie_type == IOMMU_COOKIE_DMA_IOVA ||
  1794. domain->cookie_type == IOMMU_COOKIE_DMA_MSI);
  1795. }
  1796. static size_t cookie_msi_granule(const struct iommu_domain *domain)
  1797. {
  1798. switch (domain->cookie_type) {
  1799. case IOMMU_COOKIE_DMA_IOVA:
  1800. return domain->iova_cookie->iovad.granule;
  1801. case IOMMU_COOKIE_DMA_MSI:
  1802. return PAGE_SIZE;
  1803. default:
  1804. BUG();
  1805. }
  1806. }
  1807. static struct list_head *cookie_msi_pages(const struct iommu_domain *domain)
  1808. {
  1809. switch (domain->cookie_type) {
  1810. case IOMMU_COOKIE_DMA_IOVA:
  1811. return &domain->iova_cookie->msi_page_list;
  1812. case IOMMU_COOKIE_DMA_MSI:
  1813. return &domain->msi_cookie->msi_page_list;
  1814. default:
  1815. BUG();
  1816. }
  1817. }
  1818. static struct iommu_dma_msi_page *iommu_dma_get_msi_page(struct device *dev,
  1819. phys_addr_t msi_addr, struct iommu_domain *domain)
  1820. {
  1821. struct list_head *msi_page_list = cookie_msi_pages(domain);
  1822. struct iommu_dma_msi_page *msi_page;
  1823. dma_addr_t iova;
  1824. int prot = IOMMU_WRITE | IOMMU_NOEXEC | IOMMU_MMIO;
  1825. size_t size = cookie_msi_granule(domain);
  1826. msi_addr &= ~(phys_addr_t)(size - 1);
  1827. list_for_each_entry(msi_page, msi_page_list, list)
  1828. if (msi_page->phys == msi_addr)
  1829. return msi_page;
  1830. msi_page = kzalloc_obj(*msi_page);
  1831. if (!msi_page)
  1832. return NULL;
  1833. iova = iommu_dma_alloc_iova(domain, size, dma_get_mask(dev), dev);
  1834. if (!iova)
  1835. goto out_free_page;
  1836. if (iommu_map(domain, iova, msi_addr, size, prot, GFP_KERNEL))
  1837. goto out_free_iova;
  1838. INIT_LIST_HEAD(&msi_page->list);
  1839. msi_page->phys = msi_addr;
  1840. msi_page->iova = iova;
  1841. list_add(&msi_page->list, msi_page_list);
  1842. return msi_page;
  1843. out_free_iova:
  1844. iommu_dma_free_iova(domain, iova, size, NULL);
  1845. out_free_page:
  1846. kfree(msi_page);
  1847. return NULL;
  1848. }
  1849. int iommu_dma_sw_msi(struct iommu_domain *domain, struct msi_desc *desc,
  1850. phys_addr_t msi_addr)
  1851. {
  1852. struct device *dev = msi_desc_to_dev(desc);
  1853. const struct iommu_dma_msi_page *msi_page;
  1854. if (!has_msi_cookie(domain)) {
  1855. msi_desc_set_iommu_msi_iova(desc, 0, 0);
  1856. return 0;
  1857. }
  1858. iommu_group_mutex_assert(dev);
  1859. msi_page = iommu_dma_get_msi_page(dev, msi_addr, domain);
  1860. if (!msi_page)
  1861. return -ENOMEM;
  1862. msi_desc_set_iommu_msi_iova(desc, msi_page->iova,
  1863. ilog2(cookie_msi_granule(domain)));
  1864. return 0;
  1865. }
  1866. static int iommu_dma_init(void)
  1867. {
  1868. if (is_kdump_kernel())
  1869. static_branch_enable(&iommu_deferred_attach_enabled);
  1870. return iova_cache_get();
  1871. }
  1872. arch_initcall(iommu_dma_init);