swiotlb.c 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Dynamic DMA mapping support.
  4. *
  5. * This implementation is a fallback for platforms that do not support
  6. * I/O TLBs (aka DMA address translation hardware).
  7. * Copyright (C) 2000 Asit Mallick <Asit.K.Mallick@intel.com>
  8. * Copyright (C) 2000 Goutham Rao <goutham.rao@intel.com>
  9. * Copyright (C) 2000, 2003 Hewlett-Packard Co
  10. * David Mosberger-Tang <davidm@hpl.hp.com>
  11. *
  12. * 03/05/07 davidm Switch from PCI-DMA to generic device DMA API.
  13. * 00/12/13 davidm Rename to swiotlb.c and add mark_clean() to avoid
  14. * unnecessary i-cache flushing.
  15. * 04/07/.. ak Better overflow handling. Assorted fixes.
  16. * 05/09/10 linville Add support for syncing ranges, support syncing for
  17. * DMA_BIDIRECTIONAL mappings, miscellaneous cleanup.
  18. * 08/12/11 beckyb Add highmem support
  19. */
  20. #define pr_fmt(fmt) "software IO TLB: " fmt
  21. #include <linux/cache.h>
  22. #include <linux/cc_platform.h>
  23. #include <linux/ctype.h>
  24. #include <linux/debugfs.h>
  25. #include <linux/dma-direct.h>
  26. #include <linux/dma-map-ops.h>
  27. #include <linux/export.h>
  28. #include <linux/gfp.h>
  29. #include <linux/highmem.h>
  30. #include <linux/io.h>
  31. #include <linux/iommu-helper.h>
  32. #include <linux/init.h>
  33. #include <linux/memblock.h>
  34. #include <linux/mm.h>
  35. #include <linux/pfn.h>
  36. #include <linux/rculist.h>
  37. #include <linux/scatterlist.h>
  38. #include <linux/set_memory.h>
  39. #include <linux/spinlock.h>
  40. #include <linux/string.h>
  41. #include <linux/swiotlb.h>
  42. #include <linux/types.h>
  43. #ifdef CONFIG_DMA_RESTRICTED_POOL
  44. #include <linux/of.h>
  45. #include <linux/of_fdt.h>
  46. #include <linux/of_reserved_mem.h>
  47. #include <linux/slab.h>
  48. #endif
  49. #define CREATE_TRACE_POINTS
  50. #include <trace/events/swiotlb.h>
  51. #define SLABS_PER_PAGE (1 << (PAGE_SHIFT - IO_TLB_SHIFT))
  52. /*
  53. * Minimum IO TLB size to bother booting with. Systems with mainly
  54. * 64bit capable cards will only lightly use the swiotlb. If we can't
  55. * allocate a contiguous 1MB, we're probably in trouble anyway.
  56. */
  57. #define IO_TLB_MIN_SLABS ((1<<20) >> IO_TLB_SHIFT)
  58. #define INVALID_PHYS_ADDR (~(phys_addr_t)0)
  59. /**
  60. * struct io_tlb_slot - IO TLB slot descriptor
  61. * @orig_addr: The original address corresponding to a mapped entry.
  62. * @alloc_size: Size of the allocated buffer.
  63. * @list: The free list describing the number of free entries available
  64. * from each index.
  65. * @pad_slots: Number of preceding padding slots. Valid only in the first
  66. * allocated non-padding slot.
  67. */
  68. struct io_tlb_slot {
  69. phys_addr_t orig_addr;
  70. size_t alloc_size;
  71. unsigned short list;
  72. unsigned short pad_slots;
  73. };
  74. static bool swiotlb_force_bounce;
  75. static bool swiotlb_force_disable;
  76. #ifdef CONFIG_SWIOTLB_DYNAMIC
  77. static void swiotlb_dyn_alloc(struct work_struct *work);
  78. static struct io_tlb_mem io_tlb_default_mem = {
  79. .lock = __SPIN_LOCK_UNLOCKED(io_tlb_default_mem.lock),
  80. .pools = LIST_HEAD_INIT(io_tlb_default_mem.pools),
  81. .dyn_alloc = __WORK_INITIALIZER(io_tlb_default_mem.dyn_alloc,
  82. swiotlb_dyn_alloc),
  83. };
  84. #else /* !CONFIG_SWIOTLB_DYNAMIC */
  85. static struct io_tlb_mem io_tlb_default_mem;
  86. #endif /* CONFIG_SWIOTLB_DYNAMIC */
  87. static unsigned long default_nslabs = IO_TLB_DEFAULT_SIZE >> IO_TLB_SHIFT;
  88. static unsigned long default_nareas;
  89. /**
  90. * struct io_tlb_area - IO TLB memory area descriptor
  91. *
  92. * This is a single area with a single lock.
  93. *
  94. * @used: The number of used IO TLB block.
  95. * @index: The slot index to start searching in this area for next round.
  96. * @lock: The lock to protect the above data structures in the map and
  97. * unmap calls.
  98. */
  99. struct io_tlb_area {
  100. unsigned long used;
  101. unsigned int index;
  102. spinlock_t lock;
  103. };
  104. /*
  105. * Round up number of slabs to the next power of 2. The last area is going
  106. * be smaller than the rest if default_nslabs is not power of two.
  107. * The number of slot in an area should be a multiple of IO_TLB_SEGSIZE,
  108. * otherwise a segment may span two or more areas. It conflicts with free
  109. * contiguous slots tracking: free slots are treated contiguous no matter
  110. * whether they cross an area boundary.
  111. *
  112. * Return true if default_nslabs is rounded up.
  113. */
  114. static bool round_up_default_nslabs(void)
  115. {
  116. if (!default_nareas)
  117. return false;
  118. if (default_nslabs < IO_TLB_SEGSIZE * default_nareas)
  119. default_nslabs = IO_TLB_SEGSIZE * default_nareas;
  120. else if (is_power_of_2(default_nslabs))
  121. return false;
  122. default_nslabs = roundup_pow_of_two(default_nslabs);
  123. return true;
  124. }
  125. /**
  126. * swiotlb_adjust_nareas() - adjust the number of areas and slots
  127. * @nareas: Desired number of areas. Zero is treated as 1.
  128. *
  129. * Adjust the default number of areas in a memory pool.
  130. * The default size of the memory pool may also change to meet minimum area
  131. * size requirements.
  132. */
  133. static void swiotlb_adjust_nareas(unsigned int nareas)
  134. {
  135. if (!nareas)
  136. nareas = 1;
  137. else if (!is_power_of_2(nareas))
  138. nareas = roundup_pow_of_two(nareas);
  139. default_nareas = nareas;
  140. pr_info("area num %d.\n", nareas);
  141. if (round_up_default_nslabs())
  142. pr_info("SWIOTLB bounce buffer size roundup to %luMB",
  143. (default_nslabs << IO_TLB_SHIFT) >> 20);
  144. }
  145. /**
  146. * limit_nareas() - get the maximum number of areas for a given memory pool size
  147. * @nareas: Desired number of areas.
  148. * @nslots: Total number of slots in the memory pool.
  149. *
  150. * Limit the number of areas to the maximum possible number of areas in
  151. * a memory pool of the given size.
  152. *
  153. * Return: Maximum possible number of areas.
  154. */
  155. static unsigned int limit_nareas(unsigned int nareas, unsigned long nslots)
  156. {
  157. if (nslots < nareas * IO_TLB_SEGSIZE)
  158. return nslots / IO_TLB_SEGSIZE;
  159. return nareas;
  160. }
  161. static int __init
  162. setup_io_tlb_npages(char *str)
  163. {
  164. if (isdigit(*str)) {
  165. /* avoid tail segment of size < IO_TLB_SEGSIZE */
  166. default_nslabs =
  167. ALIGN(simple_strtoul(str, &str, 0), IO_TLB_SEGSIZE);
  168. }
  169. if (*str == ',')
  170. ++str;
  171. if (isdigit(*str))
  172. swiotlb_adjust_nareas(simple_strtoul(str, &str, 0));
  173. if (*str == ',')
  174. ++str;
  175. if (!strcmp(str, "force"))
  176. swiotlb_force_bounce = true;
  177. else if (!strcmp(str, "noforce"))
  178. swiotlb_force_disable = true;
  179. return 0;
  180. }
  181. early_param("swiotlb", setup_io_tlb_npages);
  182. unsigned long swiotlb_size_or_default(void)
  183. {
  184. return default_nslabs << IO_TLB_SHIFT;
  185. }
  186. void __init swiotlb_adjust_size(unsigned long size)
  187. {
  188. /*
  189. * If swiotlb parameter has not been specified, give a chance to
  190. * architectures such as those supporting memory encryption to
  191. * adjust/expand SWIOTLB size for their use.
  192. */
  193. if (default_nslabs != IO_TLB_DEFAULT_SIZE >> IO_TLB_SHIFT)
  194. return;
  195. size = ALIGN(size, IO_TLB_SIZE);
  196. default_nslabs = ALIGN(size >> IO_TLB_SHIFT, IO_TLB_SEGSIZE);
  197. if (round_up_default_nslabs())
  198. size = default_nslabs << IO_TLB_SHIFT;
  199. pr_info("SWIOTLB bounce buffer size adjusted to %luMB", size >> 20);
  200. }
  201. void swiotlb_print_info(void)
  202. {
  203. struct io_tlb_pool *mem = &io_tlb_default_mem.defpool;
  204. if (!mem->nslabs) {
  205. pr_warn("No low mem\n");
  206. return;
  207. }
  208. pr_info("mapped [mem %pa-%pa] (%luMB)\n", &mem->start, &mem->end,
  209. (mem->nslabs << IO_TLB_SHIFT) >> 20);
  210. }
  211. static inline unsigned long io_tlb_offset(unsigned long val)
  212. {
  213. return val & (IO_TLB_SEGSIZE - 1);
  214. }
  215. static inline unsigned long nr_slots(u64 val)
  216. {
  217. return DIV_ROUND_UP(val, IO_TLB_SIZE);
  218. }
  219. /*
  220. * Early SWIOTLB allocation may be too early to allow an architecture to
  221. * perform the desired operations. This function allows the architecture to
  222. * call SWIOTLB when the operations are possible. It needs to be called
  223. * before the SWIOTLB memory is used.
  224. */
  225. void __init swiotlb_update_mem_attributes(void)
  226. {
  227. struct io_tlb_pool *mem = &io_tlb_default_mem.defpool;
  228. unsigned long bytes;
  229. if (!mem->nslabs || mem->late_alloc)
  230. return;
  231. bytes = PAGE_ALIGN(mem->nslabs << IO_TLB_SHIFT);
  232. set_memory_decrypted((unsigned long)mem->vaddr, bytes >> PAGE_SHIFT);
  233. }
  234. static void swiotlb_init_io_tlb_pool(struct io_tlb_pool *mem, phys_addr_t start,
  235. unsigned long nslabs, bool late_alloc, unsigned int nareas)
  236. {
  237. void *vaddr = phys_to_virt(start);
  238. unsigned long bytes = nslabs << IO_TLB_SHIFT, i;
  239. mem->nslabs = nslabs;
  240. mem->start = start;
  241. mem->end = mem->start + bytes;
  242. mem->late_alloc = late_alloc;
  243. mem->nareas = nareas;
  244. mem->area_nslabs = nslabs / mem->nareas;
  245. for (i = 0; i < mem->nareas; i++) {
  246. spin_lock_init(&mem->areas[i].lock);
  247. mem->areas[i].index = 0;
  248. mem->areas[i].used = 0;
  249. }
  250. for (i = 0; i < mem->nslabs; i++) {
  251. mem->slots[i].list = min(IO_TLB_SEGSIZE - io_tlb_offset(i),
  252. mem->nslabs - i);
  253. mem->slots[i].orig_addr = INVALID_PHYS_ADDR;
  254. mem->slots[i].alloc_size = 0;
  255. mem->slots[i].pad_slots = 0;
  256. }
  257. memset(vaddr, 0, bytes);
  258. mem->vaddr = vaddr;
  259. return;
  260. }
  261. /**
  262. * add_mem_pool() - add a memory pool to the allocator
  263. * @mem: Software IO TLB allocator.
  264. * @pool: Memory pool to be added.
  265. */
  266. static void add_mem_pool(struct io_tlb_mem *mem, struct io_tlb_pool *pool)
  267. {
  268. #ifdef CONFIG_SWIOTLB_DYNAMIC
  269. spin_lock(&mem->lock);
  270. list_add_rcu(&pool->node, &mem->pools);
  271. mem->nslabs += pool->nslabs;
  272. spin_unlock(&mem->lock);
  273. #else
  274. mem->nslabs = pool->nslabs;
  275. #endif
  276. }
  277. static void __init *swiotlb_memblock_alloc(unsigned long nslabs,
  278. unsigned int flags,
  279. int (*remap)(void *tlb, unsigned long nslabs))
  280. {
  281. size_t bytes = PAGE_ALIGN(nslabs << IO_TLB_SHIFT);
  282. void *tlb;
  283. /*
  284. * By default allocate the bounce buffer memory from low memory, but
  285. * allow to pick a location everywhere for hypervisors with guest
  286. * memory encryption.
  287. */
  288. if (flags & SWIOTLB_ANY)
  289. tlb = memblock_alloc(bytes, PAGE_SIZE);
  290. else
  291. tlb = memblock_alloc_low(bytes, PAGE_SIZE);
  292. if (!tlb) {
  293. pr_warn("%s: Failed to allocate %zu bytes tlb structure\n",
  294. __func__, bytes);
  295. return NULL;
  296. }
  297. if (remap && remap(tlb, nslabs) < 0) {
  298. memblock_free(tlb, PAGE_ALIGN(bytes));
  299. pr_warn("%s: Failed to remap %zu bytes\n", __func__, bytes);
  300. return NULL;
  301. }
  302. return tlb;
  303. }
  304. /*
  305. * Statically reserve bounce buffer space and initialize bounce buffer data
  306. * structures for the software IO TLB used to implement the DMA API.
  307. */
  308. void __init swiotlb_init_remap(bool addressing_limit, unsigned int flags,
  309. int (*remap)(void *tlb, unsigned long nslabs))
  310. {
  311. struct io_tlb_pool *mem = &io_tlb_default_mem.defpool;
  312. unsigned long nslabs;
  313. unsigned int nareas;
  314. size_t alloc_size;
  315. void *tlb;
  316. if (!addressing_limit && !swiotlb_force_bounce)
  317. return;
  318. if (swiotlb_force_disable)
  319. return;
  320. io_tlb_default_mem.force_bounce =
  321. swiotlb_force_bounce || (flags & SWIOTLB_FORCE);
  322. #ifdef CONFIG_SWIOTLB_DYNAMIC
  323. if (!remap)
  324. io_tlb_default_mem.can_grow = true;
  325. if (flags & SWIOTLB_ANY)
  326. io_tlb_default_mem.phys_limit = virt_to_phys(high_memory - 1);
  327. else
  328. io_tlb_default_mem.phys_limit = ARCH_LOW_ADDRESS_LIMIT;
  329. #endif
  330. if (!default_nareas)
  331. swiotlb_adjust_nareas(num_possible_cpus());
  332. nslabs = default_nslabs;
  333. nareas = limit_nareas(default_nareas, nslabs);
  334. while ((tlb = swiotlb_memblock_alloc(nslabs, flags, remap)) == NULL) {
  335. if (nslabs <= IO_TLB_MIN_SLABS)
  336. return;
  337. nslabs = ALIGN(nslabs >> 1, IO_TLB_SEGSIZE);
  338. nareas = limit_nareas(nareas, nslabs);
  339. }
  340. if (default_nslabs != nslabs) {
  341. pr_info("SWIOTLB bounce buffer size adjusted %lu -> %lu slabs",
  342. default_nslabs, nslabs);
  343. default_nslabs = nslabs;
  344. }
  345. alloc_size = PAGE_ALIGN(array_size(sizeof(*mem->slots), nslabs));
  346. mem->slots = memblock_alloc(alloc_size, PAGE_SIZE);
  347. if (!mem->slots) {
  348. pr_warn("%s: Failed to allocate %zu bytes align=0x%lx\n",
  349. __func__, alloc_size, PAGE_SIZE);
  350. return;
  351. }
  352. mem->areas = memblock_alloc(array_size(sizeof(struct io_tlb_area),
  353. nareas), SMP_CACHE_BYTES);
  354. if (!mem->areas) {
  355. pr_warn("%s: Failed to allocate mem->areas.\n", __func__);
  356. return;
  357. }
  358. swiotlb_init_io_tlb_pool(mem, __pa(tlb), nslabs, false, nareas);
  359. add_mem_pool(&io_tlb_default_mem, mem);
  360. if (flags & SWIOTLB_VERBOSE)
  361. swiotlb_print_info();
  362. }
  363. void __init swiotlb_init(bool addressing_limit, unsigned int flags)
  364. {
  365. swiotlb_init_remap(addressing_limit, flags, NULL);
  366. }
  367. /*
  368. * Systems with larger DMA zones (those that don't support ISA) can
  369. * initialize the swiotlb later using the slab allocator if needed.
  370. * This should be just like above, but with some error catching.
  371. */
  372. int swiotlb_init_late(size_t size, gfp_t gfp_mask,
  373. int (*remap)(void *tlb, unsigned long nslabs))
  374. {
  375. struct io_tlb_pool *mem = &io_tlb_default_mem.defpool;
  376. unsigned long nslabs = ALIGN(size >> IO_TLB_SHIFT, IO_TLB_SEGSIZE);
  377. unsigned int nareas;
  378. unsigned char *vstart = NULL;
  379. unsigned int order, area_order;
  380. bool retried = false;
  381. int rc = 0;
  382. if (io_tlb_default_mem.nslabs)
  383. return 0;
  384. if (swiotlb_force_disable)
  385. return 0;
  386. io_tlb_default_mem.force_bounce = swiotlb_force_bounce;
  387. #ifdef CONFIG_SWIOTLB_DYNAMIC
  388. if (!remap)
  389. io_tlb_default_mem.can_grow = true;
  390. if (IS_ENABLED(CONFIG_ZONE_DMA) && (gfp_mask & __GFP_DMA))
  391. io_tlb_default_mem.phys_limit = zone_dma_limit;
  392. else if (IS_ENABLED(CONFIG_ZONE_DMA32) && (gfp_mask & __GFP_DMA32))
  393. io_tlb_default_mem.phys_limit = max(DMA_BIT_MASK(32), zone_dma_limit);
  394. else
  395. io_tlb_default_mem.phys_limit = virt_to_phys(high_memory - 1);
  396. #endif
  397. if (!default_nareas)
  398. swiotlb_adjust_nareas(num_possible_cpus());
  399. retry:
  400. order = get_order(nslabs << IO_TLB_SHIFT);
  401. nslabs = SLABS_PER_PAGE << order;
  402. while ((SLABS_PER_PAGE << order) > IO_TLB_MIN_SLABS) {
  403. vstart = (void *)__get_free_pages(gfp_mask | __GFP_NOWARN,
  404. order);
  405. if (vstart)
  406. break;
  407. order--;
  408. nslabs = SLABS_PER_PAGE << order;
  409. retried = true;
  410. }
  411. if (!vstart)
  412. return -ENOMEM;
  413. if (remap)
  414. rc = remap(vstart, nslabs);
  415. if (rc) {
  416. free_pages((unsigned long)vstart, order);
  417. nslabs = ALIGN(nslabs >> 1, IO_TLB_SEGSIZE);
  418. if (nslabs < IO_TLB_MIN_SLABS)
  419. return rc;
  420. retried = true;
  421. goto retry;
  422. }
  423. if (retried) {
  424. pr_warn("only able to allocate %ld MB\n",
  425. (PAGE_SIZE << order) >> 20);
  426. }
  427. nareas = limit_nareas(default_nareas, nslabs);
  428. area_order = get_order(array_size(sizeof(*mem->areas), nareas));
  429. mem->areas = (struct io_tlb_area *)
  430. __get_free_pages(GFP_KERNEL | __GFP_ZERO, area_order);
  431. if (!mem->areas)
  432. goto error_area;
  433. mem->slots = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
  434. get_order(array_size(sizeof(*mem->slots), nslabs)));
  435. if (!mem->slots)
  436. goto error_slots;
  437. set_memory_decrypted((unsigned long)vstart,
  438. (nslabs << IO_TLB_SHIFT) >> PAGE_SHIFT);
  439. swiotlb_init_io_tlb_pool(mem, virt_to_phys(vstart), nslabs, true,
  440. nareas);
  441. add_mem_pool(&io_tlb_default_mem, mem);
  442. swiotlb_print_info();
  443. return 0;
  444. error_slots:
  445. free_pages((unsigned long)mem->areas, area_order);
  446. error_area:
  447. free_pages((unsigned long)vstart, order);
  448. return -ENOMEM;
  449. }
  450. void __init swiotlb_exit(void)
  451. {
  452. struct io_tlb_pool *mem = &io_tlb_default_mem.defpool;
  453. unsigned long tbl_vaddr;
  454. size_t tbl_size, slots_size;
  455. unsigned int area_order;
  456. if (swiotlb_force_bounce)
  457. return;
  458. if (!mem->nslabs)
  459. return;
  460. pr_info("tearing down default memory pool\n");
  461. tbl_vaddr = (unsigned long)phys_to_virt(mem->start);
  462. tbl_size = PAGE_ALIGN(mem->end - mem->start);
  463. slots_size = PAGE_ALIGN(array_size(sizeof(*mem->slots), mem->nslabs));
  464. set_memory_encrypted(tbl_vaddr, tbl_size >> PAGE_SHIFT);
  465. if (mem->late_alloc) {
  466. area_order = get_order(array_size(sizeof(*mem->areas),
  467. mem->nareas));
  468. free_pages((unsigned long)mem->areas, area_order);
  469. free_pages(tbl_vaddr, get_order(tbl_size));
  470. free_pages((unsigned long)mem->slots, get_order(slots_size));
  471. } else {
  472. memblock_free_late(__pa(mem->areas),
  473. array_size(sizeof(*mem->areas), mem->nareas));
  474. memblock_free_late(mem->start, tbl_size);
  475. memblock_free_late(__pa(mem->slots), slots_size);
  476. }
  477. memset(mem, 0, sizeof(*mem));
  478. }
  479. #ifdef CONFIG_SWIOTLB_DYNAMIC
  480. /**
  481. * alloc_dma_pages() - allocate pages to be used for DMA
  482. * @gfp: GFP flags for the allocation.
  483. * @bytes: Size of the buffer.
  484. * @phys_limit: Maximum allowed physical address of the buffer.
  485. *
  486. * Allocate pages from the buddy allocator. If successful, make the allocated
  487. * pages decrypted that they can be used for DMA.
  488. *
  489. * Return: Decrypted pages, %NULL on allocation failure, or ERR_PTR(-EAGAIN)
  490. * if the allocated physical address was above @phys_limit.
  491. */
  492. static struct page *alloc_dma_pages(gfp_t gfp, size_t bytes, u64 phys_limit)
  493. {
  494. unsigned int order = get_order(bytes);
  495. struct page *page;
  496. phys_addr_t paddr;
  497. void *vaddr;
  498. page = alloc_pages(gfp, order);
  499. if (!page)
  500. return NULL;
  501. paddr = page_to_phys(page);
  502. if (paddr + bytes - 1 > phys_limit) {
  503. __free_pages(page, order);
  504. return ERR_PTR(-EAGAIN);
  505. }
  506. vaddr = phys_to_virt(paddr);
  507. if (set_memory_decrypted((unsigned long)vaddr, PFN_UP(bytes)))
  508. goto error;
  509. return page;
  510. error:
  511. /* Intentional leak if pages cannot be encrypted again. */
  512. if (!set_memory_encrypted((unsigned long)vaddr, PFN_UP(bytes)))
  513. __free_pages(page, order);
  514. return NULL;
  515. }
  516. /**
  517. * swiotlb_alloc_tlb() - allocate a dynamic IO TLB buffer
  518. * @dev: Device for which a memory pool is allocated.
  519. * @bytes: Size of the buffer.
  520. * @phys_limit: Maximum allowed physical address of the buffer.
  521. * @gfp: GFP flags for the allocation.
  522. *
  523. * Return: Allocated pages, or %NULL on allocation failure.
  524. */
  525. static struct page *swiotlb_alloc_tlb(struct device *dev, size_t bytes,
  526. u64 phys_limit, gfp_t gfp)
  527. {
  528. struct page *page;
  529. /*
  530. * Allocate from the atomic pools if memory is encrypted and
  531. * the allocation is atomic, because decrypting may block.
  532. */
  533. if (!gfpflags_allow_blocking(gfp) && dev && force_dma_unencrypted(dev)) {
  534. void *vaddr;
  535. if (!IS_ENABLED(CONFIG_DMA_COHERENT_POOL))
  536. return NULL;
  537. return dma_alloc_from_pool(dev, bytes, &vaddr, gfp,
  538. dma_coherent_ok);
  539. }
  540. gfp &= ~GFP_ZONEMASK;
  541. if (phys_limit <= zone_dma_limit)
  542. gfp |= __GFP_DMA;
  543. else if (phys_limit <= DMA_BIT_MASK(32))
  544. gfp |= __GFP_DMA32;
  545. while (IS_ERR(page = alloc_dma_pages(gfp, bytes, phys_limit))) {
  546. if (IS_ENABLED(CONFIG_ZONE_DMA32) &&
  547. phys_limit < DMA_BIT_MASK(64) &&
  548. !(gfp & (__GFP_DMA32 | __GFP_DMA)))
  549. gfp |= __GFP_DMA32;
  550. else if (IS_ENABLED(CONFIG_ZONE_DMA) &&
  551. !(gfp & __GFP_DMA))
  552. gfp = (gfp & ~__GFP_DMA32) | __GFP_DMA;
  553. else
  554. return NULL;
  555. }
  556. return page;
  557. }
  558. /**
  559. * swiotlb_free_tlb() - free a dynamically allocated IO TLB buffer
  560. * @vaddr: Virtual address of the buffer.
  561. * @bytes: Size of the buffer.
  562. */
  563. static void swiotlb_free_tlb(void *vaddr, size_t bytes)
  564. {
  565. if (IS_ENABLED(CONFIG_DMA_COHERENT_POOL) &&
  566. dma_free_from_pool(NULL, vaddr, bytes))
  567. return;
  568. /* Intentional leak if pages cannot be encrypted again. */
  569. if (!set_memory_encrypted((unsigned long)vaddr, PFN_UP(bytes)))
  570. __free_pages(virt_to_page(vaddr), get_order(bytes));
  571. }
  572. /**
  573. * swiotlb_alloc_pool() - allocate a new IO TLB memory pool
  574. * @dev: Device for which a memory pool is allocated.
  575. * @minslabs: Minimum number of slabs.
  576. * @nslabs: Desired (maximum) number of slabs.
  577. * @nareas: Number of areas.
  578. * @phys_limit: Maximum DMA buffer physical address.
  579. * @gfp: GFP flags for the allocations.
  580. *
  581. * Allocate and initialize a new IO TLB memory pool. The actual number of
  582. * slabs may be reduced if allocation of @nslabs fails. If even
  583. * @minslabs cannot be allocated, this function fails.
  584. *
  585. * Return: New memory pool, or %NULL on allocation failure.
  586. */
  587. static struct io_tlb_pool *swiotlb_alloc_pool(struct device *dev,
  588. unsigned long minslabs, unsigned long nslabs,
  589. unsigned int nareas, u64 phys_limit, gfp_t gfp)
  590. {
  591. struct io_tlb_pool *pool;
  592. unsigned int slot_order;
  593. struct page *tlb;
  594. size_t pool_size;
  595. size_t tlb_size;
  596. if (nslabs > SLABS_PER_PAGE << MAX_PAGE_ORDER) {
  597. nslabs = SLABS_PER_PAGE << MAX_PAGE_ORDER;
  598. nareas = limit_nareas(nareas, nslabs);
  599. }
  600. pool_size = sizeof(*pool) + array_size(sizeof(*pool->areas), nareas);
  601. pool = kzalloc(pool_size, gfp);
  602. if (!pool)
  603. goto error;
  604. pool->areas = (void *)pool + sizeof(*pool);
  605. tlb_size = nslabs << IO_TLB_SHIFT;
  606. while (!(tlb = swiotlb_alloc_tlb(dev, tlb_size, phys_limit, gfp))) {
  607. if (nslabs <= minslabs)
  608. goto error_tlb;
  609. nslabs = ALIGN(nslabs >> 1, IO_TLB_SEGSIZE);
  610. nareas = limit_nareas(nareas, nslabs);
  611. tlb_size = nslabs << IO_TLB_SHIFT;
  612. }
  613. slot_order = get_order(array_size(sizeof(*pool->slots), nslabs));
  614. pool->slots = (struct io_tlb_slot *)
  615. __get_free_pages(gfp, slot_order);
  616. if (!pool->slots)
  617. goto error_slots;
  618. swiotlb_init_io_tlb_pool(pool, page_to_phys(tlb), nslabs, true, nareas);
  619. return pool;
  620. error_slots:
  621. swiotlb_free_tlb(page_address(tlb), tlb_size);
  622. error_tlb:
  623. kfree(pool);
  624. error:
  625. return NULL;
  626. }
  627. /**
  628. * swiotlb_dyn_alloc() - dynamic memory pool allocation worker
  629. * @work: Pointer to dyn_alloc in struct io_tlb_mem.
  630. */
  631. static void swiotlb_dyn_alloc(struct work_struct *work)
  632. {
  633. struct io_tlb_mem *mem =
  634. container_of(work, struct io_tlb_mem, dyn_alloc);
  635. struct io_tlb_pool *pool;
  636. pool = swiotlb_alloc_pool(NULL, IO_TLB_MIN_SLABS, default_nslabs,
  637. default_nareas, mem->phys_limit, GFP_KERNEL);
  638. if (!pool) {
  639. pr_warn_ratelimited("Failed to allocate new pool");
  640. return;
  641. }
  642. add_mem_pool(mem, pool);
  643. }
  644. /**
  645. * swiotlb_dyn_free() - RCU callback to free a memory pool
  646. * @rcu: RCU head in the corresponding struct io_tlb_pool.
  647. */
  648. static void swiotlb_dyn_free(struct rcu_head *rcu)
  649. {
  650. struct io_tlb_pool *pool = container_of(rcu, struct io_tlb_pool, rcu);
  651. size_t slots_size = array_size(sizeof(*pool->slots), pool->nslabs);
  652. size_t tlb_size = pool->end - pool->start;
  653. free_pages((unsigned long)pool->slots, get_order(slots_size));
  654. swiotlb_free_tlb(pool->vaddr, tlb_size);
  655. kfree(pool);
  656. }
  657. /**
  658. * __swiotlb_find_pool() - find the IO TLB pool for a physical address
  659. * @dev: Device which has mapped the DMA buffer.
  660. * @paddr: Physical address within the DMA buffer.
  661. *
  662. * Find the IO TLB memory pool descriptor which contains the given physical
  663. * address, if any. This function is for use only when the dev is known to
  664. * be using swiotlb. Use swiotlb_find_pool() for the more general case
  665. * when this condition is not met.
  666. *
  667. * Return: Memory pool which contains @paddr, or %NULL if none.
  668. */
  669. struct io_tlb_pool *__swiotlb_find_pool(struct device *dev, phys_addr_t paddr)
  670. {
  671. struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
  672. struct io_tlb_pool *pool;
  673. rcu_read_lock();
  674. list_for_each_entry_rcu(pool, &mem->pools, node) {
  675. if (paddr >= pool->start && paddr < pool->end)
  676. goto out;
  677. }
  678. list_for_each_entry_rcu(pool, &dev->dma_io_tlb_pools, node) {
  679. if (paddr >= pool->start && paddr < pool->end)
  680. goto out;
  681. }
  682. pool = NULL;
  683. out:
  684. rcu_read_unlock();
  685. return pool;
  686. }
  687. /**
  688. * swiotlb_del_pool() - remove an IO TLB pool from a device
  689. * @dev: Owning device.
  690. * @pool: Memory pool to be removed.
  691. */
  692. static void swiotlb_del_pool(struct device *dev, struct io_tlb_pool *pool)
  693. {
  694. unsigned long flags;
  695. spin_lock_irqsave(&dev->dma_io_tlb_lock, flags);
  696. list_del_rcu(&pool->node);
  697. spin_unlock_irqrestore(&dev->dma_io_tlb_lock, flags);
  698. call_rcu(&pool->rcu, swiotlb_dyn_free);
  699. }
  700. #endif /* CONFIG_SWIOTLB_DYNAMIC */
  701. /**
  702. * swiotlb_dev_init() - initialize swiotlb fields in &struct device
  703. * @dev: Device to be initialized.
  704. */
  705. void swiotlb_dev_init(struct device *dev)
  706. {
  707. dev->dma_io_tlb_mem = &io_tlb_default_mem;
  708. #ifdef CONFIG_SWIOTLB_DYNAMIC
  709. INIT_LIST_HEAD(&dev->dma_io_tlb_pools);
  710. spin_lock_init(&dev->dma_io_tlb_lock);
  711. dev->dma_uses_io_tlb = false;
  712. #endif
  713. }
  714. /**
  715. * swiotlb_align_offset() - Get required offset into an IO TLB allocation.
  716. * @dev: Owning device.
  717. * @align_mask: Allocation alignment mask.
  718. * @addr: DMA address.
  719. *
  720. * Return the minimum offset from the start of an IO TLB allocation which is
  721. * required for a given buffer address and allocation alignment to keep the
  722. * device happy.
  723. *
  724. * First, the address bits covered by min_align_mask must be identical in the
  725. * original address and the bounce buffer address. High bits are preserved by
  726. * choosing a suitable IO TLB slot, but bits below IO_TLB_SHIFT require extra
  727. * padding bytes before the bounce buffer.
  728. *
  729. * Second, @align_mask specifies which bits of the first allocated slot must
  730. * be zero. This may require allocating additional padding slots, and then the
  731. * offset (in bytes) from the first such padding slot is returned.
  732. */
  733. static unsigned int swiotlb_align_offset(struct device *dev,
  734. unsigned int align_mask, u64 addr)
  735. {
  736. return addr & dma_get_min_align_mask(dev) &
  737. (align_mask | (IO_TLB_SIZE - 1));
  738. }
  739. /*
  740. * Bounce: copy the swiotlb buffer from or back to the original dma location
  741. */
  742. static void swiotlb_bounce(struct device *dev, phys_addr_t tlb_addr, size_t size,
  743. enum dma_data_direction dir, struct io_tlb_pool *mem)
  744. {
  745. int index = (tlb_addr - mem->start) >> IO_TLB_SHIFT;
  746. phys_addr_t orig_addr = mem->slots[index].orig_addr;
  747. size_t alloc_size = mem->slots[index].alloc_size;
  748. unsigned long pfn = PFN_DOWN(orig_addr);
  749. unsigned char *vaddr = mem->vaddr + tlb_addr - mem->start;
  750. int tlb_offset;
  751. if (orig_addr == INVALID_PHYS_ADDR)
  752. return;
  753. /*
  754. * It's valid for tlb_offset to be negative. This can happen when the
  755. * "offset" returned by swiotlb_align_offset() is non-zero, and the
  756. * tlb_addr is pointing within the first "offset" bytes of the second
  757. * or subsequent slots of the allocated swiotlb area. While it's not
  758. * valid for tlb_addr to be pointing within the first "offset" bytes
  759. * of the first slot, there's no way to check for such an error since
  760. * this function can't distinguish the first slot from the second and
  761. * subsequent slots.
  762. */
  763. tlb_offset = (tlb_addr & (IO_TLB_SIZE - 1)) -
  764. swiotlb_align_offset(dev, 0, orig_addr);
  765. orig_addr += tlb_offset;
  766. alloc_size -= tlb_offset;
  767. if (size > alloc_size) {
  768. dev_WARN_ONCE(dev, 1,
  769. "Buffer overflow detected. Allocation size: %zu. Mapping size: %zu.\n",
  770. alloc_size, size);
  771. size = alloc_size;
  772. }
  773. if (PageHighMem(pfn_to_page(pfn))) {
  774. unsigned int offset = orig_addr & ~PAGE_MASK;
  775. struct page *page;
  776. unsigned int sz = 0;
  777. unsigned long flags;
  778. while (size) {
  779. sz = min_t(size_t, PAGE_SIZE - offset, size);
  780. local_irq_save(flags);
  781. page = pfn_to_page(pfn);
  782. if (dir == DMA_TO_DEVICE)
  783. memcpy_from_page(vaddr, page, offset, sz);
  784. else
  785. memcpy_to_page(page, offset, vaddr, sz);
  786. local_irq_restore(flags);
  787. size -= sz;
  788. pfn++;
  789. vaddr += sz;
  790. offset = 0;
  791. }
  792. } else if (dir == DMA_TO_DEVICE) {
  793. memcpy(vaddr, phys_to_virt(orig_addr), size);
  794. } else {
  795. memcpy(phys_to_virt(orig_addr), vaddr, size);
  796. }
  797. }
  798. static inline phys_addr_t slot_addr(phys_addr_t start, phys_addr_t idx)
  799. {
  800. return start + (idx << IO_TLB_SHIFT);
  801. }
  802. /*
  803. * Carefully handle integer overflow which can occur when boundary_mask == ~0UL.
  804. */
  805. static inline unsigned long get_max_slots(unsigned long boundary_mask)
  806. {
  807. return (boundary_mask >> IO_TLB_SHIFT) + 1;
  808. }
  809. static unsigned int wrap_area_index(struct io_tlb_pool *mem, unsigned int index)
  810. {
  811. if (index >= mem->area_nslabs)
  812. return 0;
  813. return index;
  814. }
  815. /*
  816. * Track the total used slots with a global atomic value in order to have
  817. * correct information to determine the high water mark. The mem_used()
  818. * function gives imprecise results because there's no locking across
  819. * multiple areas.
  820. */
  821. #ifdef CONFIG_DEBUG_FS
  822. static void inc_used_and_hiwater(struct io_tlb_mem *mem, unsigned int nslots)
  823. {
  824. unsigned long old_hiwater, new_used;
  825. new_used = atomic_long_add_return(nslots, &mem->total_used);
  826. old_hiwater = atomic_long_read(&mem->used_hiwater);
  827. do {
  828. if (new_used <= old_hiwater)
  829. break;
  830. } while (!atomic_long_try_cmpxchg(&mem->used_hiwater,
  831. &old_hiwater, new_used));
  832. }
  833. static void dec_used(struct io_tlb_mem *mem, unsigned int nslots)
  834. {
  835. atomic_long_sub(nslots, &mem->total_used);
  836. }
  837. #else /* !CONFIG_DEBUG_FS */
  838. static void inc_used_and_hiwater(struct io_tlb_mem *mem, unsigned int nslots)
  839. {
  840. }
  841. static void dec_used(struct io_tlb_mem *mem, unsigned int nslots)
  842. {
  843. }
  844. #endif /* CONFIG_DEBUG_FS */
  845. #ifdef CONFIG_SWIOTLB_DYNAMIC
  846. #ifdef CONFIG_DEBUG_FS
  847. static void inc_transient_used(struct io_tlb_mem *mem, unsigned int nslots)
  848. {
  849. atomic_long_add(nslots, &mem->transient_nslabs);
  850. }
  851. static void dec_transient_used(struct io_tlb_mem *mem, unsigned int nslots)
  852. {
  853. atomic_long_sub(nslots, &mem->transient_nslabs);
  854. }
  855. #else /* !CONFIG_DEBUG_FS */
  856. static void inc_transient_used(struct io_tlb_mem *mem, unsigned int nslots)
  857. {
  858. }
  859. static void dec_transient_used(struct io_tlb_mem *mem, unsigned int nslots)
  860. {
  861. }
  862. #endif /* CONFIG_DEBUG_FS */
  863. #endif /* CONFIG_SWIOTLB_DYNAMIC */
  864. /**
  865. * swiotlb_search_pool_area() - search one memory area in one pool
  866. * @dev: Device which maps the buffer.
  867. * @pool: Memory pool to be searched.
  868. * @area_index: Index of the IO TLB memory area to be searched.
  869. * @orig_addr: Original (non-bounced) IO buffer address.
  870. * @alloc_size: Total requested size of the bounce buffer,
  871. * including initial alignment padding.
  872. * @alloc_align_mask: Required alignment of the allocated buffer.
  873. *
  874. * Find a suitable sequence of IO TLB entries for the request and allocate
  875. * a buffer from the given IO TLB memory area.
  876. * This function takes care of locking.
  877. *
  878. * Return: Index of the first allocated slot, or -1 on error.
  879. */
  880. static int swiotlb_search_pool_area(struct device *dev, struct io_tlb_pool *pool,
  881. int area_index, phys_addr_t orig_addr, size_t alloc_size,
  882. unsigned int alloc_align_mask)
  883. {
  884. struct io_tlb_area *area = pool->areas + area_index;
  885. unsigned long boundary_mask = dma_get_seg_boundary(dev);
  886. dma_addr_t tbl_dma_addr =
  887. phys_to_dma_unencrypted(dev, pool->start) & boundary_mask;
  888. unsigned long max_slots = get_max_slots(boundary_mask);
  889. unsigned int iotlb_align_mask = dma_get_min_align_mask(dev);
  890. unsigned int nslots = nr_slots(alloc_size), stride;
  891. unsigned int offset = swiotlb_align_offset(dev, 0, orig_addr);
  892. unsigned int index, slots_checked, count = 0, i;
  893. unsigned long flags;
  894. unsigned int slot_base;
  895. unsigned int slot_index;
  896. BUG_ON(!nslots);
  897. BUG_ON(area_index >= pool->nareas);
  898. /*
  899. * Historically, swiotlb allocations >= PAGE_SIZE were guaranteed to be
  900. * page-aligned in the absence of any other alignment requirements.
  901. * 'alloc_align_mask' was later introduced to specify the alignment
  902. * explicitly, however this is passed as zero for streaming mappings
  903. * and so we preserve the old behaviour there in case any drivers are
  904. * relying on it.
  905. */
  906. if (!alloc_align_mask && !iotlb_align_mask && alloc_size >= PAGE_SIZE)
  907. alloc_align_mask = PAGE_SIZE - 1;
  908. /*
  909. * Ensure that the allocation is at least slot-aligned and update
  910. * 'iotlb_align_mask' to ignore bits that will be preserved when
  911. * offsetting into the allocation.
  912. */
  913. alloc_align_mask |= (IO_TLB_SIZE - 1);
  914. iotlb_align_mask &= ~alloc_align_mask;
  915. /*
  916. * For mappings with an alignment requirement don't bother looping to
  917. * unaligned slots once we found an aligned one.
  918. */
  919. stride = get_max_slots(max(alloc_align_mask, iotlb_align_mask));
  920. spin_lock_irqsave(&area->lock, flags);
  921. if (unlikely(nslots > pool->area_nslabs - area->used))
  922. goto not_found;
  923. slot_base = area_index * pool->area_nslabs;
  924. index = area->index;
  925. for (slots_checked = 0; slots_checked < pool->area_nslabs; ) {
  926. phys_addr_t tlb_addr;
  927. slot_index = slot_base + index;
  928. tlb_addr = slot_addr(tbl_dma_addr, slot_index);
  929. if ((tlb_addr & alloc_align_mask) ||
  930. (orig_addr && (tlb_addr & iotlb_align_mask) !=
  931. (orig_addr & iotlb_align_mask))) {
  932. index = wrap_area_index(pool, index + 1);
  933. slots_checked++;
  934. continue;
  935. }
  936. if (!iommu_is_span_boundary(slot_index, nslots,
  937. nr_slots(tbl_dma_addr),
  938. max_slots)) {
  939. if (pool->slots[slot_index].list >= nslots)
  940. goto found;
  941. }
  942. index = wrap_area_index(pool, index + stride);
  943. slots_checked += stride;
  944. }
  945. not_found:
  946. spin_unlock_irqrestore(&area->lock, flags);
  947. return -1;
  948. found:
  949. /*
  950. * If we find a slot that indicates we have 'nslots' number of
  951. * contiguous buffers, we allocate the buffers from that slot onwards
  952. * and set the list of free entries to '0' indicating unavailable.
  953. */
  954. for (i = slot_index; i < slot_index + nslots; i++) {
  955. pool->slots[i].list = 0;
  956. pool->slots[i].alloc_size = alloc_size - (offset +
  957. ((i - slot_index) << IO_TLB_SHIFT));
  958. }
  959. for (i = slot_index - 1;
  960. io_tlb_offset(i) != IO_TLB_SEGSIZE - 1 &&
  961. pool->slots[i].list; i--)
  962. pool->slots[i].list = ++count;
  963. /*
  964. * Update the indices to avoid searching in the next round.
  965. */
  966. area->index = wrap_area_index(pool, index + nslots);
  967. area->used += nslots;
  968. spin_unlock_irqrestore(&area->lock, flags);
  969. inc_used_and_hiwater(dev->dma_io_tlb_mem, nslots);
  970. return slot_index;
  971. }
  972. #ifdef CONFIG_SWIOTLB_DYNAMIC
  973. /**
  974. * swiotlb_search_area() - search one memory area in all pools
  975. * @dev: Device which maps the buffer.
  976. * @start_cpu: Start CPU number.
  977. * @cpu_offset: Offset from @start_cpu.
  978. * @orig_addr: Original (non-bounced) IO buffer address.
  979. * @alloc_size: Total requested size of the bounce buffer,
  980. * including initial alignment padding.
  981. * @alloc_align_mask: Required alignment of the allocated buffer.
  982. * @retpool: Used memory pool, updated on return.
  983. *
  984. * Search one memory area in all pools for a sequence of slots that match the
  985. * allocation constraints.
  986. *
  987. * Return: Index of the first allocated slot, or -1 on error.
  988. */
  989. static int swiotlb_search_area(struct device *dev, int start_cpu,
  990. int cpu_offset, phys_addr_t orig_addr, size_t alloc_size,
  991. unsigned int alloc_align_mask, struct io_tlb_pool **retpool)
  992. {
  993. struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
  994. struct io_tlb_pool *pool;
  995. int area_index;
  996. int index = -1;
  997. rcu_read_lock();
  998. list_for_each_entry_rcu(pool, &mem->pools, node) {
  999. if (cpu_offset >= pool->nareas)
  1000. continue;
  1001. area_index = (start_cpu + cpu_offset) & (pool->nareas - 1);
  1002. index = swiotlb_search_pool_area(dev, pool, area_index,
  1003. orig_addr, alloc_size,
  1004. alloc_align_mask);
  1005. if (index >= 0) {
  1006. *retpool = pool;
  1007. break;
  1008. }
  1009. }
  1010. rcu_read_unlock();
  1011. return index;
  1012. }
  1013. /**
  1014. * swiotlb_find_slots() - search for slots in the whole swiotlb
  1015. * @dev: Device which maps the buffer.
  1016. * @orig_addr: Original (non-bounced) IO buffer address.
  1017. * @alloc_size: Total requested size of the bounce buffer,
  1018. * including initial alignment padding.
  1019. * @alloc_align_mask: Required alignment of the allocated buffer.
  1020. * @retpool: Used memory pool, updated on return.
  1021. *
  1022. * Search through the whole software IO TLB to find a sequence of slots that
  1023. * match the allocation constraints.
  1024. *
  1025. * Return: Index of the first allocated slot, or -1 on error.
  1026. */
  1027. static int swiotlb_find_slots(struct device *dev, phys_addr_t orig_addr,
  1028. size_t alloc_size, unsigned int alloc_align_mask,
  1029. struct io_tlb_pool **retpool)
  1030. {
  1031. struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
  1032. struct io_tlb_pool *pool;
  1033. unsigned long nslabs;
  1034. unsigned long flags;
  1035. u64 phys_limit;
  1036. int cpu, i;
  1037. int index;
  1038. if (alloc_size > IO_TLB_SEGSIZE * IO_TLB_SIZE)
  1039. return -1;
  1040. cpu = raw_smp_processor_id();
  1041. for (i = 0; i < default_nareas; ++i) {
  1042. index = swiotlb_search_area(dev, cpu, i, orig_addr, alloc_size,
  1043. alloc_align_mask, &pool);
  1044. if (index >= 0)
  1045. goto found;
  1046. }
  1047. if (!mem->can_grow)
  1048. return -1;
  1049. schedule_work(&mem->dyn_alloc);
  1050. nslabs = nr_slots(alloc_size);
  1051. phys_limit = min_not_zero(*dev->dma_mask, dev->bus_dma_limit);
  1052. pool = swiotlb_alloc_pool(dev, nslabs, nslabs, 1, phys_limit,
  1053. GFP_NOWAIT | __GFP_NOWARN);
  1054. if (!pool)
  1055. return -1;
  1056. index = swiotlb_search_pool_area(dev, pool, 0, orig_addr,
  1057. alloc_size, alloc_align_mask);
  1058. if (index < 0) {
  1059. swiotlb_dyn_free(&pool->rcu);
  1060. return -1;
  1061. }
  1062. pool->transient = true;
  1063. spin_lock_irqsave(&dev->dma_io_tlb_lock, flags);
  1064. list_add_rcu(&pool->node, &dev->dma_io_tlb_pools);
  1065. spin_unlock_irqrestore(&dev->dma_io_tlb_lock, flags);
  1066. inc_transient_used(mem, pool->nslabs);
  1067. found:
  1068. WRITE_ONCE(dev->dma_uses_io_tlb, true);
  1069. /*
  1070. * The general barrier orders reads and writes against a presumed store
  1071. * of the SWIOTLB buffer address by a device driver (to a driver private
  1072. * data structure). It serves two purposes.
  1073. *
  1074. * First, the store to dev->dma_uses_io_tlb must be ordered before the
  1075. * presumed store. This guarantees that the returned buffer address
  1076. * cannot be passed to another CPU before updating dev->dma_uses_io_tlb.
  1077. *
  1078. * Second, the load from mem->pools must be ordered before the same
  1079. * presumed store. This guarantees that the returned buffer address
  1080. * cannot be observed by another CPU before an update of the RCU list
  1081. * that was made by swiotlb_dyn_alloc() on a third CPU (cf. multicopy
  1082. * atomicity).
  1083. *
  1084. * See also the comment in swiotlb_find_pool().
  1085. */
  1086. smp_mb();
  1087. *retpool = pool;
  1088. return index;
  1089. }
  1090. #else /* !CONFIG_SWIOTLB_DYNAMIC */
  1091. static int swiotlb_find_slots(struct device *dev, phys_addr_t orig_addr,
  1092. size_t alloc_size, unsigned int alloc_align_mask,
  1093. struct io_tlb_pool **retpool)
  1094. {
  1095. struct io_tlb_pool *pool;
  1096. int start, i;
  1097. int index;
  1098. *retpool = pool = &dev->dma_io_tlb_mem->defpool;
  1099. i = start = raw_smp_processor_id() & (pool->nareas - 1);
  1100. do {
  1101. index = swiotlb_search_pool_area(dev, pool, i, orig_addr,
  1102. alloc_size, alloc_align_mask);
  1103. if (index >= 0)
  1104. return index;
  1105. if (++i >= pool->nareas)
  1106. i = 0;
  1107. } while (i != start);
  1108. return -1;
  1109. }
  1110. #endif /* CONFIG_SWIOTLB_DYNAMIC */
  1111. #ifdef CONFIG_DEBUG_FS
  1112. /**
  1113. * mem_used() - get number of used slots in an allocator
  1114. * @mem: Software IO TLB allocator.
  1115. *
  1116. * The result is accurate in this version of the function, because an atomic
  1117. * counter is available if CONFIG_DEBUG_FS is set.
  1118. *
  1119. * Return: Number of used slots.
  1120. */
  1121. static unsigned long mem_used(struct io_tlb_mem *mem)
  1122. {
  1123. return atomic_long_read(&mem->total_used);
  1124. }
  1125. #else /* !CONFIG_DEBUG_FS */
  1126. /**
  1127. * mem_pool_used() - get number of used slots in a memory pool
  1128. * @pool: Software IO TLB memory pool.
  1129. *
  1130. * The result is not accurate, see mem_used().
  1131. *
  1132. * Return: Approximate number of used slots.
  1133. */
  1134. static unsigned long mem_pool_used(struct io_tlb_pool *pool)
  1135. {
  1136. int i;
  1137. unsigned long used = 0;
  1138. for (i = 0; i < pool->nareas; i++)
  1139. used += pool->areas[i].used;
  1140. return used;
  1141. }
  1142. /**
  1143. * mem_used() - get number of used slots in an allocator
  1144. * @mem: Software IO TLB allocator.
  1145. *
  1146. * The result is not accurate, because there is no locking of individual
  1147. * areas.
  1148. *
  1149. * Return: Approximate number of used slots.
  1150. */
  1151. static unsigned long mem_used(struct io_tlb_mem *mem)
  1152. {
  1153. #ifdef CONFIG_SWIOTLB_DYNAMIC
  1154. struct io_tlb_pool *pool;
  1155. unsigned long used = 0;
  1156. rcu_read_lock();
  1157. list_for_each_entry_rcu(pool, &mem->pools, node)
  1158. used += mem_pool_used(pool);
  1159. rcu_read_unlock();
  1160. return used;
  1161. #else
  1162. return mem_pool_used(&mem->defpool);
  1163. #endif
  1164. }
  1165. #endif /* CONFIG_DEBUG_FS */
  1166. /**
  1167. * swiotlb_tbl_map_single() - bounce buffer map a single contiguous physical area
  1168. * @dev: Device which maps the buffer.
  1169. * @orig_addr: Original (non-bounced) physical IO buffer address
  1170. * @mapping_size: Requested size of the actual bounce buffer, excluding
  1171. * any pre- or post-padding for alignment
  1172. * @alloc_align_mask: Required start and end alignment of the allocated buffer
  1173. * @dir: DMA direction
  1174. * @attrs: Optional DMA attributes for the map operation
  1175. *
  1176. * Find and allocate a suitable sequence of IO TLB slots for the request.
  1177. * The allocated space starts at an alignment specified by alloc_align_mask,
  1178. * and the size of the allocated space is rounded up so that the total amount
  1179. * of allocated space is a multiple of (alloc_align_mask + 1). If
  1180. * alloc_align_mask is zero, the allocated space may be at any alignment and
  1181. * the size is not rounded up.
  1182. *
  1183. * The returned address is within the allocated space and matches the bits
  1184. * of orig_addr that are specified in the DMA min_align_mask for the device. As
  1185. * such, this returned address may be offset from the beginning of the allocated
  1186. * space. The bounce buffer space starting at the returned address for
  1187. * mapping_size bytes is initialized to the contents of the original IO buffer
  1188. * area. Any pre-padding (due to an offset) and any post-padding (due to
  1189. * rounding-up the size) is not initialized.
  1190. */
  1191. phys_addr_t swiotlb_tbl_map_single(struct device *dev, phys_addr_t orig_addr,
  1192. size_t mapping_size, unsigned int alloc_align_mask,
  1193. enum dma_data_direction dir, unsigned long attrs)
  1194. {
  1195. struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
  1196. unsigned int offset;
  1197. struct io_tlb_pool *pool;
  1198. unsigned int i;
  1199. size_t size;
  1200. int index;
  1201. phys_addr_t tlb_addr;
  1202. unsigned short pad_slots;
  1203. if (!mem || !mem->nslabs) {
  1204. dev_warn_ratelimited(dev,
  1205. "Can not allocate SWIOTLB buffer earlier and can't now provide you with the DMA bounce buffer");
  1206. return (phys_addr_t)DMA_MAPPING_ERROR;
  1207. }
  1208. if (cc_platform_has(CC_ATTR_MEM_ENCRYPT))
  1209. pr_warn_once("Memory encryption is active and system is using DMA bounce buffers\n");
  1210. /*
  1211. * The default swiotlb memory pool is allocated with PAGE_SIZE
  1212. * alignment. If a mapping is requested with larger alignment,
  1213. * the mapping may be unable to use the initial slot(s) in all
  1214. * sets of IO_TLB_SEGSIZE slots. In such case, a mapping request
  1215. * of or near the maximum mapping size would always fail.
  1216. */
  1217. dev_WARN_ONCE(dev, alloc_align_mask > ~PAGE_MASK,
  1218. "Alloc alignment may prevent fulfilling requests with max mapping_size\n");
  1219. offset = swiotlb_align_offset(dev, alloc_align_mask, orig_addr);
  1220. size = ALIGN(mapping_size + offset, alloc_align_mask + 1);
  1221. index = swiotlb_find_slots(dev, orig_addr, size, alloc_align_mask, &pool);
  1222. if (index == -1) {
  1223. if (!(attrs & DMA_ATTR_NO_WARN))
  1224. dev_warn_ratelimited(dev,
  1225. "swiotlb buffer is full (sz: %zd bytes), total %lu (slots), used %lu (slots)\n",
  1226. size, mem->nslabs, mem_used(mem));
  1227. return (phys_addr_t)DMA_MAPPING_ERROR;
  1228. }
  1229. /*
  1230. * If dma_skip_sync was set, reset it on first SWIOTLB buffer
  1231. * mapping to always sync SWIOTLB buffers.
  1232. */
  1233. dma_reset_need_sync(dev);
  1234. /*
  1235. * Save away the mapping from the original address to the DMA address.
  1236. * This is needed when we sync the memory. Then we sync the buffer if
  1237. * needed.
  1238. */
  1239. pad_slots = offset >> IO_TLB_SHIFT;
  1240. offset &= (IO_TLB_SIZE - 1);
  1241. index += pad_slots;
  1242. pool->slots[index].pad_slots = pad_slots;
  1243. for (i = 0; i < (nr_slots(size) - pad_slots); i++)
  1244. pool->slots[index + i].orig_addr = slot_addr(orig_addr, i);
  1245. tlb_addr = slot_addr(pool->start, index) + offset;
  1246. /*
  1247. * When the device is writing memory, i.e. dir == DMA_FROM_DEVICE, copy
  1248. * the original buffer to the TLB buffer before initiating DMA in order
  1249. * to preserve the original's data if the device does a partial write,
  1250. * i.e. if the device doesn't overwrite the entire buffer. Preserving
  1251. * the original data, even if it's garbage, is necessary to match
  1252. * hardware behavior. Use of swiotlb is supposed to be transparent,
  1253. * i.e. swiotlb must not corrupt memory by clobbering unwritten bytes.
  1254. */
  1255. swiotlb_bounce(dev, tlb_addr, mapping_size, DMA_TO_DEVICE, pool);
  1256. return tlb_addr;
  1257. }
  1258. static void swiotlb_release_slots(struct device *dev, phys_addr_t tlb_addr,
  1259. struct io_tlb_pool *mem)
  1260. {
  1261. unsigned long flags;
  1262. unsigned int offset = swiotlb_align_offset(dev, 0, tlb_addr);
  1263. int index, nslots, aindex;
  1264. struct io_tlb_area *area;
  1265. int count, i;
  1266. index = (tlb_addr - offset - mem->start) >> IO_TLB_SHIFT;
  1267. index -= mem->slots[index].pad_slots;
  1268. nslots = nr_slots(mem->slots[index].alloc_size + offset);
  1269. aindex = index / mem->area_nslabs;
  1270. area = &mem->areas[aindex];
  1271. /*
  1272. * Return the buffer to the free list by setting the corresponding
  1273. * entries to indicate the number of contiguous entries available.
  1274. * While returning the entries to the free list, we merge the entries
  1275. * with slots below and above the pool being returned.
  1276. */
  1277. BUG_ON(aindex >= mem->nareas);
  1278. spin_lock_irqsave(&area->lock, flags);
  1279. if (index + nslots < ALIGN(index + 1, IO_TLB_SEGSIZE))
  1280. count = mem->slots[index + nslots].list;
  1281. else
  1282. count = 0;
  1283. /*
  1284. * Step 1: return the slots to the free list, merging the slots with
  1285. * superceeding slots
  1286. */
  1287. for (i = index + nslots - 1; i >= index; i--) {
  1288. mem->slots[i].list = ++count;
  1289. mem->slots[i].orig_addr = INVALID_PHYS_ADDR;
  1290. mem->slots[i].alloc_size = 0;
  1291. mem->slots[i].pad_slots = 0;
  1292. }
  1293. /*
  1294. * Step 2: merge the returned slots with the preceding slots, if
  1295. * available (non zero)
  1296. */
  1297. for (i = index - 1;
  1298. io_tlb_offset(i) != IO_TLB_SEGSIZE - 1 && mem->slots[i].list;
  1299. i--)
  1300. mem->slots[i].list = ++count;
  1301. area->used -= nslots;
  1302. spin_unlock_irqrestore(&area->lock, flags);
  1303. dec_used(dev->dma_io_tlb_mem, nslots);
  1304. }
  1305. #ifdef CONFIG_SWIOTLB_DYNAMIC
  1306. /**
  1307. * swiotlb_del_transient() - delete a transient memory pool
  1308. * @dev: Device which mapped the buffer.
  1309. * @tlb_addr: Physical address within a bounce buffer.
  1310. * @pool: Pointer to the transient memory pool to be checked and deleted.
  1311. *
  1312. * Check whether the address belongs to a transient SWIOTLB memory pool.
  1313. * If yes, then delete the pool.
  1314. *
  1315. * Return: %true if @tlb_addr belonged to a transient pool that was released.
  1316. */
  1317. static bool swiotlb_del_transient(struct device *dev, phys_addr_t tlb_addr,
  1318. struct io_tlb_pool *pool)
  1319. {
  1320. if (!pool->transient)
  1321. return false;
  1322. dec_used(dev->dma_io_tlb_mem, pool->nslabs);
  1323. swiotlb_del_pool(dev, pool);
  1324. dec_transient_used(dev->dma_io_tlb_mem, pool->nslabs);
  1325. return true;
  1326. }
  1327. #else /* !CONFIG_SWIOTLB_DYNAMIC */
  1328. static inline bool swiotlb_del_transient(struct device *dev,
  1329. phys_addr_t tlb_addr, struct io_tlb_pool *pool)
  1330. {
  1331. return false;
  1332. }
  1333. #endif /* CONFIG_SWIOTLB_DYNAMIC */
  1334. /*
  1335. * tlb_addr is the physical address of the bounce buffer to unmap.
  1336. */
  1337. void __swiotlb_tbl_unmap_single(struct device *dev, phys_addr_t tlb_addr,
  1338. size_t mapping_size, enum dma_data_direction dir,
  1339. unsigned long attrs, struct io_tlb_pool *pool)
  1340. {
  1341. /*
  1342. * First, sync the memory before unmapping the entry
  1343. */
  1344. if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
  1345. (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL))
  1346. swiotlb_bounce(dev, tlb_addr, mapping_size,
  1347. DMA_FROM_DEVICE, pool);
  1348. if (swiotlb_del_transient(dev, tlb_addr, pool))
  1349. return;
  1350. swiotlb_release_slots(dev, tlb_addr, pool);
  1351. }
  1352. void __swiotlb_sync_single_for_device(struct device *dev, phys_addr_t tlb_addr,
  1353. size_t size, enum dma_data_direction dir,
  1354. struct io_tlb_pool *pool)
  1355. {
  1356. if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL)
  1357. swiotlb_bounce(dev, tlb_addr, size, DMA_TO_DEVICE, pool);
  1358. else
  1359. BUG_ON(dir != DMA_FROM_DEVICE);
  1360. }
  1361. void __swiotlb_sync_single_for_cpu(struct device *dev, phys_addr_t tlb_addr,
  1362. size_t size, enum dma_data_direction dir,
  1363. struct io_tlb_pool *pool)
  1364. {
  1365. if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
  1366. swiotlb_bounce(dev, tlb_addr, size, DMA_FROM_DEVICE, pool);
  1367. else
  1368. BUG_ON(dir != DMA_TO_DEVICE);
  1369. }
  1370. /*
  1371. * Create a swiotlb mapping for the buffer at @paddr, and in case of DMAing
  1372. * to the device copy the data into it as well.
  1373. */
  1374. dma_addr_t swiotlb_map(struct device *dev, phys_addr_t paddr, size_t size,
  1375. enum dma_data_direction dir, unsigned long attrs)
  1376. {
  1377. phys_addr_t swiotlb_addr;
  1378. dma_addr_t dma_addr;
  1379. trace_swiotlb_bounced(dev, phys_to_dma(dev, paddr), size);
  1380. swiotlb_addr = swiotlb_tbl_map_single(dev, paddr, size, 0, dir, attrs);
  1381. if (swiotlb_addr == (phys_addr_t)DMA_MAPPING_ERROR)
  1382. return DMA_MAPPING_ERROR;
  1383. /* Ensure that the address returned is DMA'ble */
  1384. dma_addr = phys_to_dma_unencrypted(dev, swiotlb_addr);
  1385. if (unlikely(!dma_capable(dev, dma_addr, size, true))) {
  1386. __swiotlb_tbl_unmap_single(dev, swiotlb_addr, size, dir,
  1387. attrs | DMA_ATTR_SKIP_CPU_SYNC,
  1388. swiotlb_find_pool(dev, swiotlb_addr));
  1389. dev_WARN_ONCE(dev, 1,
  1390. "swiotlb addr %pad+%zu overflow (mask %llx, bus limit %llx).\n",
  1391. &dma_addr, size, *dev->dma_mask, dev->bus_dma_limit);
  1392. return DMA_MAPPING_ERROR;
  1393. }
  1394. if (!dev_is_dma_coherent(dev) && !(attrs & DMA_ATTR_SKIP_CPU_SYNC))
  1395. arch_sync_dma_for_device(swiotlb_addr, size, dir);
  1396. return dma_addr;
  1397. }
  1398. size_t swiotlb_max_mapping_size(struct device *dev)
  1399. {
  1400. int min_align_mask = dma_get_min_align_mask(dev);
  1401. int min_align = 0;
  1402. /*
  1403. * swiotlb_find_slots() skips slots according to
  1404. * min align mask. This affects max mapping size.
  1405. * Take it into acount here.
  1406. */
  1407. if (min_align_mask)
  1408. min_align = roundup(min_align_mask, IO_TLB_SIZE);
  1409. return ((size_t)IO_TLB_SIZE) * IO_TLB_SEGSIZE - min_align;
  1410. }
  1411. /**
  1412. * is_swiotlb_allocated() - check if the default software IO TLB is initialized
  1413. */
  1414. bool is_swiotlb_allocated(void)
  1415. {
  1416. return io_tlb_default_mem.nslabs;
  1417. }
  1418. bool is_swiotlb_active(struct device *dev)
  1419. {
  1420. struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
  1421. return mem && mem->nslabs;
  1422. }
  1423. /**
  1424. * default_swiotlb_base() - get the base address of the default SWIOTLB
  1425. *
  1426. * Get the lowest physical address used by the default software IO TLB pool.
  1427. */
  1428. phys_addr_t default_swiotlb_base(void)
  1429. {
  1430. #ifdef CONFIG_SWIOTLB_DYNAMIC
  1431. io_tlb_default_mem.can_grow = false;
  1432. #endif
  1433. return io_tlb_default_mem.defpool.start;
  1434. }
  1435. /**
  1436. * default_swiotlb_limit() - get the address limit of the default SWIOTLB
  1437. *
  1438. * Get the highest physical address used by the default software IO TLB pool.
  1439. */
  1440. phys_addr_t default_swiotlb_limit(void)
  1441. {
  1442. #ifdef CONFIG_SWIOTLB_DYNAMIC
  1443. return io_tlb_default_mem.phys_limit;
  1444. #else
  1445. return io_tlb_default_mem.defpool.end - 1;
  1446. #endif
  1447. }
  1448. #ifdef CONFIG_DEBUG_FS
  1449. #ifdef CONFIG_SWIOTLB_DYNAMIC
  1450. static unsigned long mem_transient_used(struct io_tlb_mem *mem)
  1451. {
  1452. return atomic_long_read(&mem->transient_nslabs);
  1453. }
  1454. static int io_tlb_transient_used_get(void *data, u64 *val)
  1455. {
  1456. struct io_tlb_mem *mem = data;
  1457. *val = mem_transient_used(mem);
  1458. return 0;
  1459. }
  1460. DEFINE_DEBUGFS_ATTRIBUTE(fops_io_tlb_transient_used, io_tlb_transient_used_get,
  1461. NULL, "%llu\n");
  1462. #endif /* CONFIG_SWIOTLB_DYNAMIC */
  1463. static int io_tlb_used_get(void *data, u64 *val)
  1464. {
  1465. struct io_tlb_mem *mem = data;
  1466. *val = mem_used(mem);
  1467. return 0;
  1468. }
  1469. static int io_tlb_hiwater_get(void *data, u64 *val)
  1470. {
  1471. struct io_tlb_mem *mem = data;
  1472. *val = atomic_long_read(&mem->used_hiwater);
  1473. return 0;
  1474. }
  1475. static int io_tlb_hiwater_set(void *data, u64 val)
  1476. {
  1477. struct io_tlb_mem *mem = data;
  1478. /* Only allow setting to zero */
  1479. if (val != 0)
  1480. return -EINVAL;
  1481. atomic_long_set(&mem->used_hiwater, val);
  1482. return 0;
  1483. }
  1484. DEFINE_DEBUGFS_ATTRIBUTE(fops_io_tlb_used, io_tlb_used_get, NULL, "%llu\n");
  1485. DEFINE_DEBUGFS_ATTRIBUTE(fops_io_tlb_hiwater, io_tlb_hiwater_get,
  1486. io_tlb_hiwater_set, "%llu\n");
  1487. static void swiotlb_create_debugfs_files(struct io_tlb_mem *mem,
  1488. const char *dirname)
  1489. {
  1490. mem->debugfs = debugfs_create_dir(dirname, io_tlb_default_mem.debugfs);
  1491. if (!mem->nslabs)
  1492. return;
  1493. debugfs_create_ulong("io_tlb_nslabs", 0400, mem->debugfs, &mem->nslabs);
  1494. debugfs_create_file("io_tlb_used", 0400, mem->debugfs, mem,
  1495. &fops_io_tlb_used);
  1496. debugfs_create_file("io_tlb_used_hiwater", 0600, mem->debugfs, mem,
  1497. &fops_io_tlb_hiwater);
  1498. #ifdef CONFIG_SWIOTLB_DYNAMIC
  1499. debugfs_create_file("io_tlb_transient_nslabs", 0400, mem->debugfs,
  1500. mem, &fops_io_tlb_transient_used);
  1501. #endif
  1502. }
  1503. static int __init swiotlb_create_default_debugfs(void)
  1504. {
  1505. swiotlb_create_debugfs_files(&io_tlb_default_mem, "swiotlb");
  1506. return 0;
  1507. }
  1508. late_initcall(swiotlb_create_default_debugfs);
  1509. #else /* !CONFIG_DEBUG_FS */
  1510. static inline void swiotlb_create_debugfs_files(struct io_tlb_mem *mem,
  1511. const char *dirname)
  1512. {
  1513. }
  1514. #endif /* CONFIG_DEBUG_FS */
  1515. #ifdef CONFIG_DMA_RESTRICTED_POOL
  1516. struct page *swiotlb_alloc(struct device *dev, size_t size)
  1517. {
  1518. struct io_tlb_mem *mem = dev->dma_io_tlb_mem;
  1519. struct io_tlb_pool *pool;
  1520. phys_addr_t tlb_addr;
  1521. unsigned int align;
  1522. int index;
  1523. if (!mem)
  1524. return NULL;
  1525. align = (1 << (get_order(size) + PAGE_SHIFT)) - 1;
  1526. index = swiotlb_find_slots(dev, 0, size, align, &pool);
  1527. if (index == -1)
  1528. return NULL;
  1529. tlb_addr = slot_addr(pool->start, index);
  1530. if (unlikely(!PAGE_ALIGNED(tlb_addr))) {
  1531. dev_WARN_ONCE(dev, 1, "Cannot allocate pages from non page-aligned swiotlb addr 0x%pa.\n",
  1532. &tlb_addr);
  1533. swiotlb_release_slots(dev, tlb_addr, pool);
  1534. return NULL;
  1535. }
  1536. return pfn_to_page(PFN_DOWN(tlb_addr));
  1537. }
  1538. bool swiotlb_free(struct device *dev, struct page *page, size_t size)
  1539. {
  1540. phys_addr_t tlb_addr = page_to_phys(page);
  1541. struct io_tlb_pool *pool;
  1542. pool = swiotlb_find_pool(dev, tlb_addr);
  1543. if (!pool)
  1544. return false;
  1545. swiotlb_release_slots(dev, tlb_addr, pool);
  1546. return true;
  1547. }
  1548. static int rmem_swiotlb_device_init(struct reserved_mem *rmem,
  1549. struct device *dev)
  1550. {
  1551. struct io_tlb_mem *mem = rmem->priv;
  1552. unsigned long nslabs = rmem->size >> IO_TLB_SHIFT;
  1553. /* Set Per-device io tlb area to one */
  1554. unsigned int nareas = 1;
  1555. if (PageHighMem(pfn_to_page(PHYS_PFN(rmem->base)))) {
  1556. dev_err(dev, "Restricted DMA pool must be accessible within the linear mapping.");
  1557. return -EINVAL;
  1558. }
  1559. /*
  1560. * Since multiple devices can share the same pool, the private data,
  1561. * io_tlb_mem struct, will be initialized by the first device attached
  1562. * to it.
  1563. */
  1564. if (!mem) {
  1565. struct io_tlb_pool *pool;
  1566. mem = kzalloc(sizeof(*mem), GFP_KERNEL);
  1567. if (!mem)
  1568. return -ENOMEM;
  1569. pool = &mem->defpool;
  1570. pool->slots = kcalloc(nslabs, sizeof(*pool->slots), GFP_KERNEL);
  1571. if (!pool->slots) {
  1572. kfree(mem);
  1573. return -ENOMEM;
  1574. }
  1575. pool->areas = kcalloc(nareas, sizeof(*pool->areas),
  1576. GFP_KERNEL);
  1577. if (!pool->areas) {
  1578. kfree(pool->slots);
  1579. kfree(mem);
  1580. return -ENOMEM;
  1581. }
  1582. set_memory_decrypted((unsigned long)phys_to_virt(rmem->base),
  1583. rmem->size >> PAGE_SHIFT);
  1584. swiotlb_init_io_tlb_pool(pool, rmem->base, nslabs,
  1585. false, nareas);
  1586. mem->force_bounce = true;
  1587. mem->for_alloc = true;
  1588. #ifdef CONFIG_SWIOTLB_DYNAMIC
  1589. spin_lock_init(&mem->lock);
  1590. INIT_LIST_HEAD_RCU(&mem->pools);
  1591. #endif
  1592. add_mem_pool(mem, pool);
  1593. rmem->priv = mem;
  1594. swiotlb_create_debugfs_files(mem, rmem->name);
  1595. }
  1596. dev->dma_io_tlb_mem = mem;
  1597. return 0;
  1598. }
  1599. static void rmem_swiotlb_device_release(struct reserved_mem *rmem,
  1600. struct device *dev)
  1601. {
  1602. dev->dma_io_tlb_mem = &io_tlb_default_mem;
  1603. }
  1604. static const struct reserved_mem_ops rmem_swiotlb_ops = {
  1605. .device_init = rmem_swiotlb_device_init,
  1606. .device_release = rmem_swiotlb_device_release,
  1607. };
  1608. static int __init rmem_swiotlb_setup(struct reserved_mem *rmem)
  1609. {
  1610. unsigned long node = rmem->fdt_node;
  1611. if (of_get_flat_dt_prop(node, "reusable", NULL) ||
  1612. of_get_flat_dt_prop(node, "linux,cma-default", NULL) ||
  1613. of_get_flat_dt_prop(node, "linux,dma-default", NULL) ||
  1614. of_get_flat_dt_prop(node, "no-map", NULL))
  1615. return -EINVAL;
  1616. rmem->ops = &rmem_swiotlb_ops;
  1617. pr_info("Reserved memory: created restricted DMA pool at %pa, size %ld MiB\n",
  1618. &rmem->base, (unsigned long)rmem->size / SZ_1M);
  1619. return 0;
  1620. }
  1621. RESERVEDMEM_OF_DECLARE(dma, "restricted-dma-pool", rmem_swiotlb_setup);
  1622. #endif /* CONFIG_DMA_RESTRICTED_POOL */