dma-buf.c 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Framework for buffer objects that can be shared across devices/subsystems.
  4. *
  5. * Copyright(C) 2011 Linaro Limited. All rights reserved.
  6. * Author: Sumit Semwal <[email protected]>
  7. *
  8. * Many thanks to linaro-mm-sig list, and specially
  9. * Arnd Bergmann <[email protected]>, Rob Clark <[email protected]> and
  10. * Daniel Vetter <[email protected]> for their support in creation and
  11. * refining of this idea.
  12. */
  13. #include <linux/fs.h>
  14. #include <linux/slab.h>
  15. #include <linux/dma-buf.h>
  16. #include <linux/dma-fence.h>
  17. #include <linux/dma-fence-unwrap.h>
  18. #include <linux/anon_inodes.h>
  19. #include <linux/export.h>
  20. #include <linux/debugfs.h>
  21. #include <linux/module.h>
  22. #include <linux/seq_file.h>
  23. #include <linux/sync_file.h>
  24. #include <linux/poll.h>
  25. #include <linux/dma-resv.h>
  26. #include <linux/mm.h>
  27. #include <linux/mount.h>
  28. #include <linux/pseudo_fs.h>
  29. #include <trace/hooks/dmabuf.h>
  30. #include <uapi/linux/dma-buf.h>
  31. #include <uapi/linux/magic.h>
  32. #include "dma-buf-sysfs-stats.h"
  33. struct dma_buf_list {
  34. struct list_head head;
  35. struct mutex lock;
  36. };
  37. static struct dma_buf_list db_list;
  38. /**
  39. * dma_buf_get_each - Helps in traversing the db_list and calls the
  40. * callback function which can extract required info out of each
  41. * dmabuf.
  42. * The db_list needs to be locked to prevent the db_list from being
  43. * dynamically updated during the traversal process.
  44. *
  45. * @callback: [in] Handle for each dmabuf buffer in db_list.
  46. * @private: [in] User-defined, used to pass in when callback is
  47. * called.
  48. *
  49. * Returns 0 on success, otherwise returns a non-zero value for
  50. * mutex_lock_interruptible or callback.
  51. */
  52. int dma_buf_get_each(int (*callback)(const struct dma_buf *dmabuf,
  53. void *private), void *private)
  54. {
  55. struct dma_buf *buf;
  56. int ret = mutex_lock_interruptible(&db_list.lock);
  57. if (ret)
  58. return ret;
  59. list_for_each_entry(buf, &db_list.head, list_node) {
  60. ret = callback(buf, private);
  61. if (ret)
  62. break;
  63. }
  64. mutex_unlock(&db_list.lock);
  65. return ret;
  66. }
  67. EXPORT_SYMBOL_NS_GPL(dma_buf_get_each, MINIDUMP);
  68. static char *dmabuffs_dname(struct dentry *dentry, char *buffer, int buflen)
  69. {
  70. struct dma_buf *dmabuf;
  71. char name[DMA_BUF_NAME_LEN];
  72. size_t ret = 0;
  73. dmabuf = dentry->d_fsdata;
  74. spin_lock(&dmabuf->name_lock);
  75. if (dmabuf->name)
  76. ret = strlcpy(name, dmabuf->name, DMA_BUF_NAME_LEN);
  77. spin_unlock(&dmabuf->name_lock);
  78. return dynamic_dname(buffer, buflen, "/%s:%s",
  79. dentry->d_name.name, ret > 0 ? name : "");
  80. }
  81. static void dma_buf_release(struct dentry *dentry)
  82. {
  83. struct dma_buf *dmabuf;
  84. dmabuf = dentry->d_fsdata;
  85. if (unlikely(!dmabuf))
  86. return;
  87. BUG_ON(dmabuf->vmapping_counter);
  88. /*
  89. * If you hit this BUG() it could mean:
  90. * * There's a file reference imbalance in dma_buf_poll / dma_buf_poll_cb or somewhere else
  91. * * dmabuf->cb_in/out.active are non-0 despite no pending fence callback
  92. */
  93. BUG_ON(dmabuf->cb_in.active || dmabuf->cb_out.active);
  94. dma_buf_stats_teardown(dmabuf);
  95. dmabuf->ops->release(dmabuf);
  96. if (dmabuf->resv == (struct dma_resv *)&dmabuf[1])
  97. dma_resv_fini(dmabuf->resv);
  98. WARN_ON(!list_empty(&dmabuf->attachments));
  99. module_put(dmabuf->owner);
  100. kfree(dmabuf->name);
  101. kfree(dmabuf);
  102. }
  103. static int dma_buf_file_release(struct inode *inode, struct file *file)
  104. {
  105. struct dma_buf *dmabuf;
  106. if (!is_dma_buf_file(file))
  107. return -EINVAL;
  108. dmabuf = file->private_data;
  109. if (dmabuf) {
  110. mutex_lock(&db_list.lock);
  111. list_del(&dmabuf->list_node);
  112. mutex_unlock(&db_list.lock);
  113. }
  114. return 0;
  115. }
  116. static const struct dentry_operations dma_buf_dentry_ops = {
  117. .d_dname = dmabuffs_dname,
  118. .d_release = dma_buf_release,
  119. };
  120. static struct vfsmount *dma_buf_mnt;
  121. static int dma_buf_fs_init_context(struct fs_context *fc)
  122. {
  123. struct pseudo_fs_context *ctx;
  124. ctx = init_pseudo(fc, DMA_BUF_MAGIC);
  125. if (!ctx)
  126. return -ENOMEM;
  127. ctx->dops = &dma_buf_dentry_ops;
  128. return 0;
  129. }
  130. static struct file_system_type dma_buf_fs_type = {
  131. .name = "dmabuf",
  132. .init_fs_context = dma_buf_fs_init_context,
  133. .kill_sb = kill_anon_super,
  134. };
  135. static int dma_buf_mmap_internal(struct file *file, struct vm_area_struct *vma)
  136. {
  137. struct dma_buf *dmabuf;
  138. bool ignore_bounds = false;
  139. if (!is_dma_buf_file(file))
  140. return -EINVAL;
  141. dmabuf = file->private_data;
  142. /* check if buffer supports mmap */
  143. if (!dmabuf->ops->mmap)
  144. return -EINVAL;
  145. trace_android_vh_ignore_dmabuf_vmap_bounds(dmabuf, &ignore_bounds);
  146. /* check for overflowing the buffer's size */
  147. if ((vma->vm_pgoff + vma_pages(vma) >
  148. dmabuf->size >> PAGE_SHIFT) && !ignore_bounds)
  149. return -EINVAL;
  150. return dmabuf->ops->mmap(dmabuf, vma);
  151. }
  152. static loff_t dma_buf_llseek(struct file *file, loff_t offset, int whence)
  153. {
  154. struct dma_buf *dmabuf;
  155. loff_t base;
  156. if (!is_dma_buf_file(file))
  157. return -EBADF;
  158. dmabuf = file->private_data;
  159. /* only support discovering the end of the buffer,
  160. but also allow SEEK_SET to maintain the idiomatic
  161. SEEK_END(0), SEEK_CUR(0) pattern */
  162. if (whence == SEEK_END)
  163. base = dmabuf->size;
  164. else if (whence == SEEK_SET)
  165. base = 0;
  166. else
  167. return -EINVAL;
  168. if (offset != 0)
  169. return -EINVAL;
  170. return base + offset;
  171. }
  172. /**
  173. * DOC: implicit fence polling
  174. *
  175. * To support cross-device and cross-driver synchronization of buffer access
  176. * implicit fences (represented internally in the kernel with &struct dma_fence)
  177. * can be attached to a &dma_buf. The glue for that and a few related things are
  178. * provided in the &dma_resv structure.
  179. *
  180. * Userspace can query the state of these implicitly tracked fences using poll()
  181. * and related system calls:
  182. *
  183. * - Checking for EPOLLIN, i.e. read access, can be use to query the state of the
  184. * most recent write or exclusive fence.
  185. *
  186. * - Checking for EPOLLOUT, i.e. write access, can be used to query the state of
  187. * all attached fences, shared and exclusive ones.
  188. *
  189. * Note that this only signals the completion of the respective fences, i.e. the
  190. * DMA transfers are complete. Cache flushing and any other necessary
  191. * preparations before CPU access can begin still need to happen.
  192. *
  193. * As an alternative to poll(), the set of fences on DMA buffer can be
  194. * exported as a &sync_file using &dma_buf_sync_file_export.
  195. */
  196. static void dma_buf_poll_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
  197. {
  198. struct dma_buf_poll_cb_t *dcb = (struct dma_buf_poll_cb_t *)cb;
  199. struct dma_buf *dmabuf = container_of(dcb->poll, struct dma_buf, poll);
  200. unsigned long flags;
  201. spin_lock_irqsave(&dcb->poll->lock, flags);
  202. wake_up_locked_poll(dcb->poll, dcb->active);
  203. dcb->active = 0;
  204. spin_unlock_irqrestore(&dcb->poll->lock, flags);
  205. dma_fence_put(fence);
  206. /* Paired with get_file in dma_buf_poll */
  207. fput(dmabuf->file);
  208. }
  209. static bool dma_buf_poll_add_cb(struct dma_resv *resv, bool write,
  210. struct dma_buf_poll_cb_t *dcb)
  211. {
  212. struct dma_resv_iter cursor;
  213. struct dma_fence *fence;
  214. int r;
  215. dma_resv_for_each_fence(&cursor, resv, dma_resv_usage_rw(write),
  216. fence) {
  217. dma_fence_get(fence);
  218. r = dma_fence_add_callback(fence, &dcb->cb, dma_buf_poll_cb);
  219. if (!r)
  220. return true;
  221. dma_fence_put(fence);
  222. }
  223. return false;
  224. }
  225. static __poll_t dma_buf_poll(struct file *file, poll_table *poll)
  226. {
  227. struct dma_buf *dmabuf;
  228. struct dma_resv *resv;
  229. __poll_t events;
  230. dmabuf = file->private_data;
  231. if (!dmabuf || !dmabuf->resv)
  232. return EPOLLERR;
  233. resv = dmabuf->resv;
  234. poll_wait(file, &dmabuf->poll, poll);
  235. events = poll_requested_events(poll) & (EPOLLIN | EPOLLOUT);
  236. if (!events)
  237. return 0;
  238. dma_resv_lock(resv, NULL);
  239. if (events & EPOLLOUT) {
  240. struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_out;
  241. /* Check that callback isn't busy */
  242. spin_lock_irq(&dmabuf->poll.lock);
  243. if (dcb->active)
  244. events &= ~EPOLLOUT;
  245. else
  246. dcb->active = EPOLLOUT;
  247. spin_unlock_irq(&dmabuf->poll.lock);
  248. if (events & EPOLLOUT) {
  249. /* Paired with fput in dma_buf_poll_cb */
  250. get_file(dmabuf->file);
  251. if (!dma_buf_poll_add_cb(resv, true, dcb))
  252. /* No callback queued, wake up any other waiters */
  253. dma_buf_poll_cb(NULL, &dcb->cb);
  254. else
  255. events &= ~EPOLLOUT;
  256. }
  257. }
  258. if (events & EPOLLIN) {
  259. struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_in;
  260. /* Check that callback isn't busy */
  261. spin_lock_irq(&dmabuf->poll.lock);
  262. if (dcb->active)
  263. events &= ~EPOLLIN;
  264. else
  265. dcb->active = EPOLLIN;
  266. spin_unlock_irq(&dmabuf->poll.lock);
  267. if (events & EPOLLIN) {
  268. /* Paired with fput in dma_buf_poll_cb */
  269. get_file(dmabuf->file);
  270. if (!dma_buf_poll_add_cb(resv, false, dcb))
  271. /* No callback queued, wake up any other waiters */
  272. dma_buf_poll_cb(NULL, &dcb->cb);
  273. else
  274. events &= ~EPOLLIN;
  275. }
  276. }
  277. dma_resv_unlock(resv);
  278. return events;
  279. }
  280. static long _dma_buf_set_name(struct dma_buf *dmabuf, const char *name)
  281. {
  282. spin_lock(&dmabuf->name_lock);
  283. kfree(dmabuf->name);
  284. dmabuf->name = name;
  285. spin_unlock(&dmabuf->name_lock);
  286. return 0;
  287. }
  288. /**
  289. * dma_buf_set_name - Set a name to a specific dma_buf to track the usage.
  290. * It could support changing the name of the dma-buf if the same
  291. * piece of memory is used for multiple purpose between different devices.
  292. *
  293. * @dmabuf: [in] dmabuf buffer that will be renamed.
  294. * @buf: [in] A piece of userspace memory that contains the name of
  295. * the dma-buf.
  296. *
  297. * Returns 0 on success. If the dma-buf buffer is already attached to
  298. * devices, return -EBUSY.
  299. *
  300. */
  301. long dma_buf_set_name(struct dma_buf *dmabuf, const char *name)
  302. {
  303. long ret = 0;
  304. char *buf = kstrndup(name, DMA_BUF_NAME_LEN, GFP_KERNEL);
  305. if (!buf)
  306. return -ENOMEM;
  307. ret = _dma_buf_set_name(dmabuf, buf);
  308. if (ret)
  309. kfree(buf);
  310. return ret;
  311. }
  312. EXPORT_SYMBOL_GPL(dma_buf_set_name);
  313. static long dma_buf_set_name_user(struct dma_buf *dmabuf, const char __user *buf)
  314. {
  315. char *name = strndup_user(buf, DMA_BUF_NAME_LEN);
  316. long ret = 0;
  317. if (IS_ERR(name))
  318. return PTR_ERR(name);
  319. ret = _dma_buf_set_name(dmabuf, name);
  320. if (ret)
  321. kfree(name);
  322. return ret;
  323. }
  324. #if IS_ENABLED(CONFIG_SYNC_FILE)
  325. static long dma_buf_export_sync_file(struct dma_buf *dmabuf,
  326. void __user *user_data)
  327. {
  328. struct dma_buf_export_sync_file arg;
  329. enum dma_resv_usage usage;
  330. struct dma_fence *fence = NULL;
  331. struct sync_file *sync_file;
  332. int fd, ret;
  333. if (copy_from_user(&arg, user_data, sizeof(arg)))
  334. return -EFAULT;
  335. if (arg.flags & ~DMA_BUF_SYNC_RW)
  336. return -EINVAL;
  337. if ((arg.flags & DMA_BUF_SYNC_RW) == 0)
  338. return -EINVAL;
  339. fd = get_unused_fd_flags(O_CLOEXEC);
  340. if (fd < 0)
  341. return fd;
  342. usage = dma_resv_usage_rw(arg.flags & DMA_BUF_SYNC_WRITE);
  343. ret = dma_resv_get_singleton(dmabuf->resv, usage, &fence);
  344. if (ret)
  345. goto err_put_fd;
  346. if (!fence)
  347. fence = dma_fence_get_stub();
  348. sync_file = sync_file_create(fence);
  349. dma_fence_put(fence);
  350. if (!sync_file) {
  351. ret = -ENOMEM;
  352. goto err_put_fd;
  353. }
  354. arg.fd = fd;
  355. if (copy_to_user(user_data, &arg, sizeof(arg))) {
  356. ret = -EFAULT;
  357. goto err_put_file;
  358. }
  359. fd_install(fd, sync_file->file);
  360. return 0;
  361. err_put_file:
  362. fput(sync_file->file);
  363. err_put_fd:
  364. put_unused_fd(fd);
  365. return ret;
  366. }
  367. static long dma_buf_import_sync_file(struct dma_buf *dmabuf,
  368. const void __user *user_data)
  369. {
  370. struct dma_buf_import_sync_file arg;
  371. struct dma_fence *fence, *f;
  372. enum dma_resv_usage usage;
  373. struct dma_fence_unwrap iter;
  374. unsigned int num_fences;
  375. int ret = 0;
  376. if (copy_from_user(&arg, user_data, sizeof(arg)))
  377. return -EFAULT;
  378. if (arg.flags & ~DMA_BUF_SYNC_RW)
  379. return -EINVAL;
  380. if ((arg.flags & DMA_BUF_SYNC_RW) == 0)
  381. return -EINVAL;
  382. fence = sync_file_get_fence(arg.fd);
  383. if (!fence)
  384. return -EINVAL;
  385. usage = (arg.flags & DMA_BUF_SYNC_WRITE) ? DMA_RESV_USAGE_WRITE :
  386. DMA_RESV_USAGE_READ;
  387. num_fences = 0;
  388. dma_fence_unwrap_for_each(f, &iter, fence)
  389. ++num_fences;
  390. if (num_fences > 0) {
  391. dma_resv_lock(dmabuf->resv, NULL);
  392. ret = dma_resv_reserve_fences(dmabuf->resv, num_fences);
  393. if (!ret) {
  394. dma_fence_unwrap_for_each(f, &iter, fence)
  395. dma_resv_add_fence(dmabuf->resv, f, usage);
  396. }
  397. dma_resv_unlock(dmabuf->resv);
  398. }
  399. dma_fence_put(fence);
  400. return ret;
  401. }
  402. #endif
  403. static long dma_buf_ioctl(struct file *file,
  404. unsigned int cmd, unsigned long arg)
  405. {
  406. struct dma_buf *dmabuf;
  407. struct dma_buf_sync sync;
  408. enum dma_data_direction direction;
  409. int ret;
  410. dmabuf = file->private_data;
  411. switch (cmd) {
  412. case DMA_BUF_IOCTL_SYNC:
  413. if (copy_from_user(&sync, (void __user *) arg, sizeof(sync)))
  414. return -EFAULT;
  415. if (sync.flags & ~DMA_BUF_SYNC_VALID_FLAGS_MASK)
  416. return -EINVAL;
  417. switch (sync.flags & DMA_BUF_SYNC_RW) {
  418. case DMA_BUF_SYNC_READ:
  419. direction = DMA_FROM_DEVICE;
  420. break;
  421. case DMA_BUF_SYNC_WRITE:
  422. direction = DMA_TO_DEVICE;
  423. break;
  424. case DMA_BUF_SYNC_RW:
  425. direction = DMA_BIDIRECTIONAL;
  426. break;
  427. default:
  428. return -EINVAL;
  429. }
  430. if (sync.flags & DMA_BUF_SYNC_END)
  431. ret = dma_buf_end_cpu_access(dmabuf, direction);
  432. else
  433. ret = dma_buf_begin_cpu_access(dmabuf, direction);
  434. return ret;
  435. case DMA_BUF_SET_NAME_A:
  436. case DMA_BUF_SET_NAME_B:
  437. return dma_buf_set_name_user(dmabuf, (const char __user *)arg);
  438. #if IS_ENABLED(CONFIG_SYNC_FILE)
  439. case DMA_BUF_IOCTL_EXPORT_SYNC_FILE:
  440. return dma_buf_export_sync_file(dmabuf, (void __user *)arg);
  441. case DMA_BUF_IOCTL_IMPORT_SYNC_FILE:
  442. return dma_buf_import_sync_file(dmabuf, (const void __user *)arg);
  443. #endif
  444. default:
  445. return -ENOTTY;
  446. }
  447. }
  448. static void dma_buf_show_fdinfo(struct seq_file *m, struct file *file)
  449. {
  450. struct dma_buf *dmabuf = file->private_data;
  451. seq_printf(m, "size:\t%zu\n", dmabuf->size);
  452. /* Don't count the temporary reference taken inside procfs seq_show */
  453. seq_printf(m, "count:\t%ld\n", file_count(dmabuf->file) - 1);
  454. seq_printf(m, "exp_name:\t%s\n", dmabuf->exp_name);
  455. spin_lock(&dmabuf->name_lock);
  456. if (dmabuf->name)
  457. seq_printf(m, "name:\t%s\n", dmabuf->name);
  458. spin_unlock(&dmabuf->name_lock);
  459. }
  460. static const struct file_operations dma_buf_fops = {
  461. .release = dma_buf_file_release,
  462. .mmap = dma_buf_mmap_internal,
  463. .llseek = dma_buf_llseek,
  464. .poll = dma_buf_poll,
  465. .unlocked_ioctl = dma_buf_ioctl,
  466. .compat_ioctl = compat_ptr_ioctl,
  467. .show_fdinfo = dma_buf_show_fdinfo,
  468. };
  469. /*
  470. * is_dma_buf_file - Check if struct file* is associated with dma_buf
  471. */
  472. int is_dma_buf_file(struct file *file)
  473. {
  474. return file->f_op == &dma_buf_fops;
  475. }
  476. EXPORT_SYMBOL_NS_GPL(is_dma_buf_file, DMA_BUF);
  477. static struct file *dma_buf_getfile(size_t size, int flags)
  478. {
  479. static atomic64_t dmabuf_inode = ATOMIC64_INIT(0);
  480. struct inode *inode = alloc_anon_inode(dma_buf_mnt->mnt_sb);
  481. struct file *file;
  482. if (IS_ERR(inode))
  483. return ERR_CAST(inode);
  484. inode->i_size = size;
  485. inode_set_bytes(inode, size);
  486. /*
  487. * The ->i_ino acquired from get_next_ino() is not unique thus
  488. * not suitable for using it as dentry name by dmabuf stats.
  489. * Override ->i_ino with the unique and dmabuffs specific
  490. * value.
  491. */
  492. inode->i_ino = atomic64_add_return(1, &dmabuf_inode);
  493. flags &= O_ACCMODE | O_NONBLOCK;
  494. file = alloc_file_pseudo(inode, dma_buf_mnt, "dmabuf",
  495. flags, &dma_buf_fops);
  496. if (IS_ERR(file))
  497. goto err_alloc_file;
  498. return file;
  499. err_alloc_file:
  500. iput(inode);
  501. return file;
  502. }
  503. /**
  504. * DOC: dma buf device access
  505. *
  506. * For device DMA access to a shared DMA buffer the usual sequence of operations
  507. * is fairly simple:
  508. *
  509. * 1. The exporter defines his exporter instance using
  510. * DEFINE_DMA_BUF_EXPORT_INFO() and calls dma_buf_export() to wrap a private
  511. * buffer object into a &dma_buf. It then exports that &dma_buf to userspace
  512. * as a file descriptor by calling dma_buf_fd().
  513. *
  514. * 2. Userspace passes this file-descriptors to all drivers it wants this buffer
  515. * to share with: First the file descriptor is converted to a &dma_buf using
  516. * dma_buf_get(). Then the buffer is attached to the device using
  517. * dma_buf_attach().
  518. *
  519. * Up to this stage the exporter is still free to migrate or reallocate the
  520. * backing storage.
  521. *
  522. * 3. Once the buffer is attached to all devices userspace can initiate DMA
  523. * access to the shared buffer. In the kernel this is done by calling
  524. * dma_buf_map_attachment() and dma_buf_unmap_attachment().
  525. *
  526. * 4. Once a driver is done with a shared buffer it needs to call
  527. * dma_buf_detach() (after cleaning up any mappings) and then release the
  528. * reference acquired with dma_buf_get() by calling dma_buf_put().
  529. *
  530. * For the detailed semantics exporters are expected to implement see
  531. * &dma_buf_ops.
  532. */
  533. /**
  534. * dma_buf_export - Creates a new dma_buf, and associates an anon file
  535. * with this buffer, so it can be exported.
  536. * Also connect the allocator specific data and ops to the buffer.
  537. * Additionally, provide a name string for exporter; useful in debugging.
  538. *
  539. * @exp_info: [in] holds all the export related information provided
  540. * by the exporter. see &struct dma_buf_export_info
  541. * for further details.
  542. *
  543. * Returns, on success, a newly created struct dma_buf object, which wraps the
  544. * supplied private data and operations for struct dma_buf_ops. On either
  545. * missing ops, or error in allocating struct dma_buf, will return negative
  546. * error.
  547. *
  548. * For most cases the easiest way to create @exp_info is through the
  549. * %DEFINE_DMA_BUF_EXPORT_INFO macro.
  550. */
  551. struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)
  552. {
  553. struct dma_buf *dmabuf;
  554. struct dma_resv *resv = exp_info->resv;
  555. struct file *file;
  556. size_t alloc_size = sizeof(struct dma_buf);
  557. int ret;
  558. if (WARN_ON(!exp_info->priv || !exp_info->ops
  559. || !exp_info->ops->map_dma_buf
  560. || !exp_info->ops->unmap_dma_buf
  561. || !exp_info->ops->release))
  562. return ERR_PTR(-EINVAL);
  563. if (WARN_ON(exp_info->ops->cache_sgt_mapping &&
  564. (exp_info->ops->pin || exp_info->ops->unpin)))
  565. return ERR_PTR(-EINVAL);
  566. if (WARN_ON(!exp_info->ops->pin != !exp_info->ops->unpin))
  567. return ERR_PTR(-EINVAL);
  568. if (!try_module_get(exp_info->owner))
  569. return ERR_PTR(-ENOENT);
  570. file = dma_buf_getfile(exp_info->size, exp_info->flags);
  571. if (IS_ERR(file)) {
  572. ret = PTR_ERR(file);
  573. goto err_module;
  574. }
  575. if (!exp_info->resv)
  576. alloc_size += sizeof(struct dma_resv);
  577. else
  578. /* prevent &dma_buf[1] == dma_buf->resv */
  579. alloc_size += 1;
  580. dmabuf = kzalloc(alloc_size, GFP_KERNEL);
  581. if (!dmabuf) {
  582. ret = -ENOMEM;
  583. goto err_file;
  584. }
  585. dmabuf->priv = exp_info->priv;
  586. dmabuf->ops = exp_info->ops;
  587. dmabuf->size = exp_info->size;
  588. dmabuf->exp_name = exp_info->exp_name;
  589. dmabuf->owner = exp_info->owner;
  590. spin_lock_init(&dmabuf->name_lock);
  591. init_waitqueue_head(&dmabuf->poll);
  592. dmabuf->cb_in.poll = dmabuf->cb_out.poll = &dmabuf->poll;
  593. dmabuf->cb_in.active = dmabuf->cb_out.active = 0;
  594. mutex_init(&dmabuf->lock);
  595. INIT_LIST_HEAD(&dmabuf->attachments);
  596. if (!resv) {
  597. dmabuf->resv = (struct dma_resv *)&dmabuf[1];
  598. dma_resv_init(dmabuf->resv);
  599. } else {
  600. dmabuf->resv = resv;
  601. }
  602. file->private_data = dmabuf;
  603. file->f_path.dentry->d_fsdata = dmabuf;
  604. dmabuf->file = file;
  605. mutex_lock(&db_list.lock);
  606. list_add(&dmabuf->list_node, &db_list.head);
  607. mutex_unlock(&db_list.lock);
  608. ret = dma_buf_stats_setup(dmabuf, file);
  609. if (ret)
  610. goto err_sysfs;
  611. return dmabuf;
  612. err_sysfs:
  613. mutex_lock(&db_list.lock);
  614. list_del(&dmabuf->list_node);
  615. mutex_unlock(&db_list.lock);
  616. dmabuf->file = NULL;
  617. file->f_path.dentry->d_fsdata = NULL;
  618. file->private_data = NULL;
  619. if (!resv)
  620. dma_resv_fini(dmabuf->resv);
  621. kfree(dmabuf);
  622. err_file:
  623. fput(file);
  624. err_module:
  625. module_put(exp_info->owner);
  626. return ERR_PTR(ret);
  627. }
  628. EXPORT_SYMBOL_NS_GPL(dma_buf_export, DMA_BUF);
  629. /**
  630. * dma_buf_fd - returns a file descriptor for the given struct dma_buf
  631. * @dmabuf: [in] pointer to dma_buf for which fd is required.
  632. * @flags: [in] flags to give to fd
  633. *
  634. * On success, returns an associated 'fd'. Else, returns error.
  635. */
  636. int dma_buf_fd(struct dma_buf *dmabuf, int flags)
  637. {
  638. int fd;
  639. if (!dmabuf || !dmabuf->file)
  640. return -EINVAL;
  641. fd = get_unused_fd_flags(flags);
  642. if (fd < 0)
  643. return fd;
  644. fd_install(fd, dmabuf->file);
  645. return fd;
  646. }
  647. EXPORT_SYMBOL_NS_GPL(dma_buf_fd, DMA_BUF);
  648. /**
  649. * dma_buf_get - returns the struct dma_buf related to an fd
  650. * @fd: [in] fd associated with the struct dma_buf to be returned
  651. *
  652. * On success, returns the struct dma_buf associated with an fd; uses
  653. * file's refcounting done by fget to increase refcount. returns ERR_PTR
  654. * otherwise.
  655. */
  656. struct dma_buf *dma_buf_get(int fd)
  657. {
  658. struct file *file;
  659. file = fget(fd);
  660. if (!file)
  661. return ERR_PTR(-EBADF);
  662. if (!is_dma_buf_file(file)) {
  663. fput(file);
  664. return ERR_PTR(-EINVAL);
  665. }
  666. return file->private_data;
  667. }
  668. EXPORT_SYMBOL_NS_GPL(dma_buf_get, DMA_BUF);
  669. /**
  670. * dma_buf_put - decreases refcount of the buffer
  671. * @dmabuf: [in] buffer to reduce refcount of
  672. *
  673. * Uses file's refcounting done implicitly by fput().
  674. *
  675. * If, as a result of this call, the refcount becomes 0, the 'release' file
  676. * operation related to this fd is called. It calls &dma_buf_ops.release vfunc
  677. * in turn, and frees the memory allocated for dmabuf when exported.
  678. */
  679. void dma_buf_put(struct dma_buf *dmabuf)
  680. {
  681. if (WARN_ON(!dmabuf || !dmabuf->file))
  682. return;
  683. fput(dmabuf->file);
  684. }
  685. EXPORT_SYMBOL_NS_GPL(dma_buf_put, DMA_BUF);
  686. static void mangle_sg_table(struct sg_table *sg_table)
  687. {
  688. #ifdef CONFIG_DMABUF_DEBUG
  689. int i;
  690. struct scatterlist *sg;
  691. /* To catch abuse of the underlying struct page by importers mix
  692. * up the bits, but take care to preserve the low SG_ bits to
  693. * not corrupt the sgt. The mixing is undone in __unmap_dma_buf
  694. * before passing the sgt back to the exporter. */
  695. for_each_sgtable_sg(sg_table, sg, i)
  696. sg->page_link ^= ~0xffUL;
  697. #endif
  698. }
  699. static struct sg_table * __map_dma_buf(struct dma_buf_attachment *attach,
  700. enum dma_data_direction direction)
  701. {
  702. struct sg_table *sg_table;
  703. signed long ret;
  704. sg_table = attach->dmabuf->ops->map_dma_buf(attach, direction);
  705. if (IS_ERR_OR_NULL(sg_table))
  706. return sg_table;
  707. if (!dma_buf_attachment_is_dynamic(attach)) {
  708. ret = dma_resv_wait_timeout(attach->dmabuf->resv,
  709. DMA_RESV_USAGE_KERNEL, true,
  710. MAX_SCHEDULE_TIMEOUT);
  711. if (ret < 0) {
  712. attach->dmabuf->ops->unmap_dma_buf(attach, sg_table,
  713. direction);
  714. return ERR_PTR(ret);
  715. }
  716. }
  717. mangle_sg_table(sg_table);
  718. return sg_table;
  719. }
  720. /**
  721. * dma_buf_dynamic_attach - Add the device to dma_buf's attachments list
  722. * @dmabuf: [in] buffer to attach device to.
  723. * @dev: [in] device to be attached.
  724. * @importer_ops: [in] importer operations for the attachment
  725. * @importer_priv: [in] importer private pointer for the attachment
  726. *
  727. * Returns struct dma_buf_attachment pointer for this attachment. Attachments
  728. * must be cleaned up by calling dma_buf_detach().
  729. *
  730. * Optionally this calls &dma_buf_ops.attach to allow device-specific attach
  731. * functionality.
  732. *
  733. * Returns:
  734. *
  735. * A pointer to newly created &dma_buf_attachment on success, or a negative
  736. * error code wrapped into a pointer on failure.
  737. *
  738. * Note that this can fail if the backing storage of @dmabuf is in a place not
  739. * accessible to @dev, and cannot be moved to a more suitable place. This is
  740. * indicated with the error code -EBUSY.
  741. */
  742. struct dma_buf_attachment *
  743. dma_buf_dynamic_attach(struct dma_buf *dmabuf, struct device *dev,
  744. const struct dma_buf_attach_ops *importer_ops,
  745. void *importer_priv)
  746. {
  747. struct dma_buf_attachment *attach;
  748. int ret;
  749. if (WARN_ON(!dmabuf || !dev))
  750. return ERR_PTR(-EINVAL);
  751. if (WARN_ON(importer_ops && !importer_ops->move_notify))
  752. return ERR_PTR(-EINVAL);
  753. attach = kzalloc(sizeof(*attach), GFP_KERNEL);
  754. if (!attach)
  755. return ERR_PTR(-ENOMEM);
  756. attach->dev = dev;
  757. attach->dmabuf = dmabuf;
  758. if (importer_ops)
  759. attach->peer2peer = importer_ops->allow_peer2peer;
  760. attach->importer_ops = importer_ops;
  761. attach->importer_priv = importer_priv;
  762. if (dmabuf->ops->attach) {
  763. ret = dmabuf->ops->attach(dmabuf, attach);
  764. if (ret)
  765. goto err_attach;
  766. }
  767. dma_resv_lock(dmabuf->resv, NULL);
  768. list_add(&attach->node, &dmabuf->attachments);
  769. dma_resv_unlock(dmabuf->resv);
  770. /* When either the importer or the exporter can't handle dynamic
  771. * mappings we cache the mapping here to avoid issues with the
  772. * reservation object lock.
  773. */
  774. if (dma_buf_attachment_is_dynamic(attach) !=
  775. dma_buf_is_dynamic(dmabuf)) {
  776. struct sg_table *sgt;
  777. if (dma_buf_is_dynamic(attach->dmabuf)) {
  778. dma_resv_lock(attach->dmabuf->resv, NULL);
  779. ret = dmabuf->ops->pin(attach);
  780. if (ret)
  781. goto err_unlock;
  782. }
  783. sgt = __map_dma_buf(attach, DMA_BIDIRECTIONAL);
  784. if (!sgt)
  785. sgt = ERR_PTR(-ENOMEM);
  786. if (IS_ERR(sgt)) {
  787. ret = PTR_ERR(sgt);
  788. goto err_unpin;
  789. }
  790. if (dma_buf_is_dynamic(attach->dmabuf))
  791. dma_resv_unlock(attach->dmabuf->resv);
  792. attach->sgt = sgt;
  793. attach->dir = DMA_BIDIRECTIONAL;
  794. }
  795. return attach;
  796. err_attach:
  797. kfree(attach);
  798. return ERR_PTR(ret);
  799. err_unpin:
  800. if (dma_buf_is_dynamic(attach->dmabuf))
  801. dmabuf->ops->unpin(attach);
  802. err_unlock:
  803. if (dma_buf_is_dynamic(attach->dmabuf))
  804. dma_resv_unlock(attach->dmabuf->resv);
  805. dma_buf_detach(dmabuf, attach);
  806. return ERR_PTR(ret);
  807. }
  808. EXPORT_SYMBOL_NS_GPL(dma_buf_dynamic_attach, DMA_BUF);
  809. /**
  810. * dma_buf_attach - Wrapper for dma_buf_dynamic_attach
  811. * @dmabuf: [in] buffer to attach device to.
  812. * @dev: [in] device to be attached.
  813. *
  814. * Wrapper to call dma_buf_dynamic_attach() for drivers which still use a static
  815. * mapping.
  816. */
  817. struct dma_buf_attachment *dma_buf_attach(struct dma_buf *dmabuf,
  818. struct device *dev)
  819. {
  820. return dma_buf_dynamic_attach(dmabuf, dev, NULL, NULL);
  821. }
  822. EXPORT_SYMBOL_NS_GPL(dma_buf_attach, DMA_BUF);
  823. static void __unmap_dma_buf(struct dma_buf_attachment *attach,
  824. struct sg_table *sg_table,
  825. enum dma_data_direction direction)
  826. {
  827. /* uses XOR, hence this unmangles */
  828. mangle_sg_table(sg_table);
  829. attach->dmabuf->ops->unmap_dma_buf(attach, sg_table, direction);
  830. }
  831. /**
  832. * dma_buf_detach - Remove the given attachment from dmabuf's attachments list
  833. * @dmabuf: [in] buffer to detach from.
  834. * @attach: [in] attachment to be detached; is free'd after this call.
  835. *
  836. * Clean up a device attachment obtained by calling dma_buf_attach().
  837. *
  838. * Optionally this calls &dma_buf_ops.detach for device-specific detach.
  839. */
  840. void dma_buf_detach(struct dma_buf *dmabuf, struct dma_buf_attachment *attach)
  841. {
  842. if (WARN_ON(!dmabuf || !attach))
  843. return;
  844. if (attach->sgt) {
  845. if (dma_buf_is_dynamic(attach->dmabuf))
  846. dma_resv_lock(attach->dmabuf->resv, NULL);
  847. __unmap_dma_buf(attach, attach->sgt, attach->dir);
  848. if (dma_buf_is_dynamic(attach->dmabuf)) {
  849. dmabuf->ops->unpin(attach);
  850. dma_resv_unlock(attach->dmabuf->resv);
  851. }
  852. }
  853. dma_resv_lock(dmabuf->resv, NULL);
  854. list_del(&attach->node);
  855. dma_resv_unlock(dmabuf->resv);
  856. if (dmabuf->ops->detach)
  857. dmabuf->ops->detach(dmabuf, attach);
  858. kfree(attach);
  859. }
  860. EXPORT_SYMBOL_NS_GPL(dma_buf_detach, DMA_BUF);
  861. /**
  862. * dma_buf_pin - Lock down the DMA-buf
  863. * @attach: [in] attachment which should be pinned
  864. *
  865. * Only dynamic importers (who set up @attach with dma_buf_dynamic_attach()) may
  866. * call this, and only for limited use cases like scanout and not for temporary
  867. * pin operations. It is not permitted to allow userspace to pin arbitrary
  868. * amounts of buffers through this interface.
  869. *
  870. * Buffers must be unpinned by calling dma_buf_unpin().
  871. *
  872. * Returns:
  873. * 0 on success, negative error code on failure.
  874. */
  875. int dma_buf_pin(struct dma_buf_attachment *attach)
  876. {
  877. struct dma_buf *dmabuf = attach->dmabuf;
  878. int ret = 0;
  879. WARN_ON(!dma_buf_attachment_is_dynamic(attach));
  880. dma_resv_assert_held(dmabuf->resv);
  881. if (dmabuf->ops->pin)
  882. ret = dmabuf->ops->pin(attach);
  883. return ret;
  884. }
  885. EXPORT_SYMBOL_NS_GPL(dma_buf_pin, DMA_BUF);
  886. /**
  887. * dma_buf_unpin - Unpin a DMA-buf
  888. * @attach: [in] attachment which should be unpinned
  889. *
  890. * This unpins a buffer pinned by dma_buf_pin() and allows the exporter to move
  891. * any mapping of @attach again and inform the importer through
  892. * &dma_buf_attach_ops.move_notify.
  893. */
  894. void dma_buf_unpin(struct dma_buf_attachment *attach)
  895. {
  896. struct dma_buf *dmabuf = attach->dmabuf;
  897. WARN_ON(!dma_buf_attachment_is_dynamic(attach));
  898. dma_resv_assert_held(dmabuf->resv);
  899. if (dmabuf->ops->unpin)
  900. dmabuf->ops->unpin(attach);
  901. }
  902. EXPORT_SYMBOL_NS_GPL(dma_buf_unpin, DMA_BUF);
  903. /**
  904. * dma_buf_map_attachment - Returns the scatterlist table of the attachment;
  905. * mapped into _device_ address space. Is a wrapper for map_dma_buf() of the
  906. * dma_buf_ops.
  907. * @attach: [in] attachment whose scatterlist is to be returned
  908. * @direction: [in] direction of DMA transfer
  909. *
  910. * Returns sg_table containing the scatterlist to be returned; returns ERR_PTR
  911. * on error. May return -EINTR if it is interrupted by a signal.
  912. *
  913. * On success, the DMA addresses and lengths in the returned scatterlist are
  914. * PAGE_SIZE aligned.
  915. *
  916. * A mapping must be unmapped by using dma_buf_unmap_attachment(). Note that
  917. * the underlying backing storage is pinned for as long as a mapping exists,
  918. * therefore users/importers should not hold onto a mapping for undue amounts of
  919. * time.
  920. *
  921. * Important: Dynamic importers must wait for the exclusive fence of the struct
  922. * dma_resv attached to the DMA-BUF first.
  923. */
  924. struct sg_table *dma_buf_map_attachment(struct dma_buf_attachment *attach,
  925. enum dma_data_direction direction)
  926. {
  927. struct sg_table *sg_table;
  928. int r;
  929. might_sleep();
  930. if (WARN_ON(!attach || !attach->dmabuf))
  931. return ERR_PTR(-EINVAL);
  932. if (dma_buf_attachment_is_dynamic(attach))
  933. dma_resv_assert_held(attach->dmabuf->resv);
  934. if (attach->sgt) {
  935. /*
  936. * Two mappings with different directions for the same
  937. * attachment are not allowed.
  938. */
  939. if (attach->dir != direction &&
  940. attach->dir != DMA_BIDIRECTIONAL)
  941. return ERR_PTR(-EBUSY);
  942. return attach->sgt;
  943. }
  944. if (dma_buf_is_dynamic(attach->dmabuf)) {
  945. dma_resv_assert_held(attach->dmabuf->resv);
  946. if (!IS_ENABLED(CONFIG_DMABUF_MOVE_NOTIFY)) {
  947. r = attach->dmabuf->ops->pin(attach);
  948. if (r)
  949. return ERR_PTR(r);
  950. }
  951. }
  952. sg_table = __map_dma_buf(attach, direction);
  953. if (!sg_table)
  954. sg_table = ERR_PTR(-ENOMEM);
  955. if (IS_ERR(sg_table) && dma_buf_is_dynamic(attach->dmabuf) &&
  956. !IS_ENABLED(CONFIG_DMABUF_MOVE_NOTIFY))
  957. attach->dmabuf->ops->unpin(attach);
  958. if (!IS_ERR(sg_table) && attach->dmabuf->ops->cache_sgt_mapping) {
  959. attach->sgt = sg_table;
  960. attach->dir = direction;
  961. }
  962. #ifdef CONFIG_DMA_API_DEBUG
  963. if (!IS_ERR(sg_table)) {
  964. struct scatterlist *sg;
  965. u64 addr;
  966. int len;
  967. int i;
  968. for_each_sgtable_dma_sg(sg_table, sg, i) {
  969. addr = sg_dma_address(sg);
  970. len = sg_dma_len(sg);
  971. if (!PAGE_ALIGNED(addr) || !PAGE_ALIGNED(len)) {
  972. pr_debug("%s: addr %llx or len %x is not page aligned!\n",
  973. __func__, addr, len);
  974. }
  975. }
  976. }
  977. #endif /* CONFIG_DMA_API_DEBUG */
  978. return sg_table;
  979. }
  980. EXPORT_SYMBOL_NS_GPL(dma_buf_map_attachment, DMA_BUF);
  981. /**
  982. * dma_buf_map_attachment_unlocked - Returns the scatterlist table of the attachment;
  983. * mapped into _device_ address space. Is a wrapper for map_dma_buf() of the
  984. * dma_buf_ops.
  985. * @attach: [in] attachment whose scatterlist is to be returned
  986. * @direction: [in] direction of DMA transfer
  987. *
  988. * Unlocked variant of dma_buf_map_attachment().
  989. */
  990. struct sg_table *
  991. dma_buf_map_attachment_unlocked(struct dma_buf_attachment *attach,
  992. enum dma_data_direction direction)
  993. {
  994. struct sg_table *sg_table;
  995. might_sleep();
  996. if (WARN_ON(!attach || !attach->dmabuf))
  997. return ERR_PTR(-EINVAL);
  998. dma_resv_lock(attach->dmabuf->resv, NULL);
  999. sg_table = dma_buf_map_attachment(attach, direction);
  1000. dma_resv_unlock(attach->dmabuf->resv);
  1001. return sg_table;
  1002. }
  1003. EXPORT_SYMBOL_NS_GPL(dma_buf_map_attachment_unlocked, DMA_BUF);
  1004. /**
  1005. * dma_buf_unmap_attachment - unmaps and decreases usecount of the buffer;might
  1006. * deallocate the scatterlist associated. Is a wrapper for unmap_dma_buf() of
  1007. * dma_buf_ops.
  1008. * @attach: [in] attachment to unmap buffer from
  1009. * @sg_table: [in] scatterlist info of the buffer to unmap
  1010. * @direction: [in] direction of DMA transfer
  1011. *
  1012. * This unmaps a DMA mapping for @attached obtained by dma_buf_map_attachment().
  1013. */
  1014. void dma_buf_unmap_attachment(struct dma_buf_attachment *attach,
  1015. struct sg_table *sg_table,
  1016. enum dma_data_direction direction)
  1017. {
  1018. might_sleep();
  1019. if (WARN_ON(!attach || !attach->dmabuf || !sg_table))
  1020. return;
  1021. if (dma_buf_attachment_is_dynamic(attach))
  1022. dma_resv_assert_held(attach->dmabuf->resv);
  1023. if (attach->sgt == sg_table)
  1024. return;
  1025. if (dma_buf_is_dynamic(attach->dmabuf))
  1026. dma_resv_assert_held(attach->dmabuf->resv);
  1027. __unmap_dma_buf(attach, sg_table, direction);
  1028. if (dma_buf_is_dynamic(attach->dmabuf) &&
  1029. !IS_ENABLED(CONFIG_DMABUF_MOVE_NOTIFY))
  1030. dma_buf_unpin(attach);
  1031. }
  1032. EXPORT_SYMBOL_NS_GPL(dma_buf_unmap_attachment, DMA_BUF);
  1033. /**
  1034. * dma_buf_unmap_attachment_unlocked - unmaps and decreases usecount of the buffer;might
  1035. * deallocate the scatterlist associated. Is a wrapper for unmap_dma_buf() of
  1036. * dma_buf_ops.
  1037. * @attach: [in] attachment to unmap buffer from
  1038. * @sg_table: [in] scatterlist info of the buffer to unmap
  1039. * @direction: [in] direction of DMA transfer
  1040. *
  1041. * Unlocked variant of dma_buf_unmap_attachment().
  1042. */
  1043. void dma_buf_unmap_attachment_unlocked(struct dma_buf_attachment *attach,
  1044. struct sg_table *sg_table,
  1045. enum dma_data_direction direction)
  1046. {
  1047. might_sleep();
  1048. if (WARN_ON(!attach || !attach->dmabuf || !sg_table))
  1049. return;
  1050. dma_resv_lock(attach->dmabuf->resv, NULL);
  1051. dma_buf_unmap_attachment(attach, sg_table, direction);
  1052. dma_resv_unlock(attach->dmabuf->resv);
  1053. }
  1054. EXPORT_SYMBOL_NS_GPL(dma_buf_unmap_attachment_unlocked, DMA_BUF);
  1055. /**
  1056. * dma_buf_move_notify - notify attachments that DMA-buf is moving
  1057. *
  1058. * @dmabuf: [in] buffer which is moving
  1059. *
  1060. * Informs all attachmenst that they need to destroy and recreated all their
  1061. * mappings.
  1062. */
  1063. void dma_buf_move_notify(struct dma_buf *dmabuf)
  1064. {
  1065. struct dma_buf_attachment *attach;
  1066. dma_resv_assert_held(dmabuf->resv);
  1067. list_for_each_entry(attach, &dmabuf->attachments, node)
  1068. if (attach->importer_ops)
  1069. attach->importer_ops->move_notify(attach);
  1070. }
  1071. EXPORT_SYMBOL_NS_GPL(dma_buf_move_notify, DMA_BUF);
  1072. /**
  1073. * DOC: cpu access
  1074. *
  1075. * There are mutliple reasons for supporting CPU access to a dma buffer object:
  1076. *
  1077. * - Fallback operations in the kernel, for example when a device is connected
  1078. * over USB and the kernel needs to shuffle the data around first before
  1079. * sending it away. Cache coherency is handled by braketing any transactions
  1080. * with calls to dma_buf_begin_cpu_access() and dma_buf_end_cpu_access()
  1081. * access.
  1082. *
  1083. * Since for most kernel internal dma-buf accesses need the entire buffer, a
  1084. * vmap interface is introduced. Note that on very old 32-bit architectures
  1085. * vmalloc space might be limited and result in vmap calls failing.
  1086. *
  1087. * Interfaces::
  1088. *
  1089. * void \*dma_buf_vmap(struct dma_buf \*dmabuf, struct iosys_map \*map)
  1090. * void dma_buf_vunmap(struct dma_buf \*dmabuf, struct iosys_map \*map)
  1091. *
  1092. * The vmap call can fail if there is no vmap support in the exporter, or if
  1093. * it runs out of vmalloc space. Note that the dma-buf layer keeps a reference
  1094. * count for all vmap access and calls down into the exporter's vmap function
  1095. * only when no vmapping exists, and only unmaps it once. Protection against
  1096. * concurrent vmap/vunmap calls is provided by taking the &dma_buf.lock mutex.
  1097. *
  1098. * - For full compatibility on the importer side with existing userspace
  1099. * interfaces, which might already support mmap'ing buffers. This is needed in
  1100. * many processing pipelines (e.g. feeding a software rendered image into a
  1101. * hardware pipeline, thumbnail creation, snapshots, ...). Also, Android's ION
  1102. * framework already supported this and for DMA buffer file descriptors to
  1103. * replace ION buffers mmap support was needed.
  1104. *
  1105. * There is no special interfaces, userspace simply calls mmap on the dma-buf
  1106. * fd. But like for CPU access there's a need to braket the actual access,
  1107. * which is handled by the ioctl (DMA_BUF_IOCTL_SYNC). Note that
  1108. * DMA_BUF_IOCTL_SYNC can fail with -EAGAIN or -EINTR, in which case it must
  1109. * be restarted.
  1110. *
  1111. * Some systems might need some sort of cache coherency management e.g. when
  1112. * CPU and GPU domains are being accessed through dma-buf at the same time.
  1113. * To circumvent this problem there are begin/end coherency markers, that
  1114. * forward directly to existing dma-buf device drivers vfunc hooks. Userspace
  1115. * can make use of those markers through the DMA_BUF_IOCTL_SYNC ioctl. The
  1116. * sequence would be used like following:
  1117. *
  1118. * - mmap dma-buf fd
  1119. * - for each drawing/upload cycle in CPU 1. SYNC_START ioctl, 2. read/write
  1120. * to mmap area 3. SYNC_END ioctl. This can be repeated as often as you
  1121. * want (with the new data being consumed by say the GPU or the scanout
  1122. * device)
  1123. * - munmap once you don't need the buffer any more
  1124. *
  1125. * For correctness and optimal performance, it is always required to use
  1126. * SYNC_START and SYNC_END before and after, respectively, when accessing the
  1127. * mapped address. Userspace cannot rely on coherent access, even when there
  1128. * are systems where it just works without calling these ioctls.
  1129. *
  1130. * - And as a CPU fallback in userspace processing pipelines.
  1131. *
  1132. * Similar to the motivation for kernel cpu access it is again important that
  1133. * the userspace code of a given importing subsystem can use the same
  1134. * interfaces with a imported dma-buf buffer object as with a native buffer
  1135. * object. This is especially important for drm where the userspace part of
  1136. * contemporary OpenGL, X, and other drivers is huge, and reworking them to
  1137. * use a different way to mmap a buffer rather invasive.
  1138. *
  1139. * The assumption in the current dma-buf interfaces is that redirecting the
  1140. * initial mmap is all that's needed. A survey of some of the existing
  1141. * subsystems shows that no driver seems to do any nefarious thing like
  1142. * syncing up with outstanding asynchronous processing on the device or
  1143. * allocating special resources at fault time. So hopefully this is good
  1144. * enough, since adding interfaces to intercept pagefaults and allow pte
  1145. * shootdowns would increase the complexity quite a bit.
  1146. *
  1147. * Interface::
  1148. *
  1149. * int dma_buf_mmap(struct dma_buf \*, struct vm_area_struct \*,
  1150. * unsigned long);
  1151. *
  1152. * If the importing subsystem simply provides a special-purpose mmap call to
  1153. * set up a mapping in userspace, calling do_mmap with &dma_buf.file will
  1154. * equally achieve that for a dma-buf object.
  1155. */
  1156. static int __dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
  1157. enum dma_data_direction direction)
  1158. {
  1159. bool write = (direction == DMA_BIDIRECTIONAL ||
  1160. direction == DMA_TO_DEVICE);
  1161. struct dma_resv *resv = dmabuf->resv;
  1162. long ret;
  1163. /* Wait on any implicit rendering fences */
  1164. ret = dma_resv_wait_timeout(resv, dma_resv_usage_rw(write),
  1165. true, MAX_SCHEDULE_TIMEOUT);
  1166. if (ret < 0)
  1167. return ret;
  1168. return 0;
  1169. }
  1170. /**
  1171. * dma_buf_begin_cpu_access - Must be called before accessing a dma_buf from the
  1172. * cpu in the kernel context. Calls begin_cpu_access to allow exporter-specific
  1173. * preparations. Coherency is only guaranteed in the specified range for the
  1174. * specified access direction.
  1175. * @dmabuf: [in] buffer to prepare cpu access for.
  1176. * @direction: [in] length of range for cpu access.
  1177. *
  1178. * After the cpu access is complete the caller should call
  1179. * dma_buf_end_cpu_access(). Only when cpu access is braketed by both calls is
  1180. * it guaranteed to be coherent with other DMA access.
  1181. *
  1182. * This function will also wait for any DMA transactions tracked through
  1183. * implicit synchronization in &dma_buf.resv. For DMA transactions with explicit
  1184. * synchronization this function will only ensure cache coherency, callers must
  1185. * ensure synchronization with such DMA transactions on their own.
  1186. *
  1187. * Can return negative error values, returns 0 on success.
  1188. */
  1189. int dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
  1190. enum dma_data_direction direction)
  1191. {
  1192. int ret = 0;
  1193. if (WARN_ON(!dmabuf))
  1194. return -EINVAL;
  1195. might_lock(&dmabuf->resv->lock.base);
  1196. if (dmabuf->ops->begin_cpu_access)
  1197. ret = dmabuf->ops->begin_cpu_access(dmabuf, direction);
  1198. /* Ensure that all fences are waited upon - but we first allow
  1199. * the native handler the chance to do so more efficiently if it
  1200. * chooses. A double invocation here will be reasonably cheap no-op.
  1201. */
  1202. if (ret == 0)
  1203. ret = __dma_buf_begin_cpu_access(dmabuf, direction);
  1204. return ret;
  1205. }
  1206. EXPORT_SYMBOL_NS_GPL(dma_buf_begin_cpu_access, DMA_BUF);
  1207. int dma_buf_begin_cpu_access_partial(struct dma_buf *dmabuf,
  1208. enum dma_data_direction direction,
  1209. unsigned int offset, unsigned int len)
  1210. {
  1211. int ret = 0;
  1212. if (WARN_ON(!dmabuf))
  1213. return -EINVAL;
  1214. if (dmabuf->ops->begin_cpu_access_partial)
  1215. ret = dmabuf->ops->begin_cpu_access_partial(dmabuf, direction,
  1216. offset, len);
  1217. /* Ensure that all fences are waited upon - but we first allow
  1218. * the native handler the chance to do so more efficiently if it
  1219. * chooses. A double invocation here will be reasonably cheap no-op.
  1220. */
  1221. if (ret == 0)
  1222. ret = __dma_buf_begin_cpu_access(dmabuf, direction);
  1223. return ret;
  1224. }
  1225. EXPORT_SYMBOL_GPL(dma_buf_begin_cpu_access_partial);
  1226. /**
  1227. * dma_buf_end_cpu_access - Must be called after accessing a dma_buf from the
  1228. * cpu in the kernel context. Calls end_cpu_access to allow exporter-specific
  1229. * actions. Coherency is only guaranteed in the specified range for the
  1230. * specified access direction.
  1231. * @dmabuf: [in] buffer to complete cpu access for.
  1232. * @direction: [in] length of range for cpu access.
  1233. *
  1234. * This terminates CPU access started with dma_buf_begin_cpu_access().
  1235. *
  1236. * Can return negative error values, returns 0 on success.
  1237. */
  1238. int dma_buf_end_cpu_access(struct dma_buf *dmabuf,
  1239. enum dma_data_direction direction)
  1240. {
  1241. int ret = 0;
  1242. WARN_ON(!dmabuf);
  1243. might_lock(&dmabuf->resv->lock.base);
  1244. if (dmabuf->ops->end_cpu_access)
  1245. ret = dmabuf->ops->end_cpu_access(dmabuf, direction);
  1246. return ret;
  1247. }
  1248. EXPORT_SYMBOL_NS_GPL(dma_buf_end_cpu_access, DMA_BUF);
  1249. int dma_buf_end_cpu_access_partial(struct dma_buf *dmabuf,
  1250. enum dma_data_direction direction,
  1251. unsigned int offset, unsigned int len)
  1252. {
  1253. int ret = 0;
  1254. WARN_ON(!dmabuf);
  1255. if (dmabuf->ops->end_cpu_access_partial)
  1256. ret = dmabuf->ops->end_cpu_access_partial(dmabuf, direction,
  1257. offset, len);
  1258. return ret;
  1259. }
  1260. EXPORT_SYMBOL_GPL(dma_buf_end_cpu_access_partial);
  1261. /**
  1262. * dma_buf_mmap - Setup up a userspace mmap with the given vma
  1263. * @dmabuf: [in] buffer that should back the vma
  1264. * @vma: [in] vma for the mmap
  1265. * @pgoff: [in] offset in pages where this mmap should start within the
  1266. * dma-buf buffer.
  1267. *
  1268. * This function adjusts the passed in vma so that it points at the file of the
  1269. * dma_buf operation. It also adjusts the starting pgoff and does bounds
  1270. * checking on the size of the vma. Then it calls the exporters mmap function to
  1271. * set up the mapping.
  1272. *
  1273. * Can return negative error values, returns 0 on success.
  1274. */
  1275. int dma_buf_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma,
  1276. unsigned long pgoff)
  1277. {
  1278. if (WARN_ON(!dmabuf || !vma))
  1279. return -EINVAL;
  1280. /* check if buffer supports mmap */
  1281. if (!dmabuf->ops->mmap)
  1282. return -EINVAL;
  1283. /* check for offset overflow */
  1284. if (pgoff + vma_pages(vma) < pgoff)
  1285. return -EOVERFLOW;
  1286. /* check for overflowing the buffer's size */
  1287. if (pgoff + vma_pages(vma) >
  1288. dmabuf->size >> PAGE_SHIFT)
  1289. return -EINVAL;
  1290. /* readjust the vma */
  1291. vma_set_file(vma, dmabuf->file);
  1292. vma->vm_pgoff = pgoff;
  1293. return dmabuf->ops->mmap(dmabuf, vma);
  1294. }
  1295. EXPORT_SYMBOL_NS_GPL(dma_buf_mmap, DMA_BUF);
  1296. /**
  1297. * dma_buf_vmap - Create virtual mapping for the buffer object into kernel
  1298. * address space. Same restrictions as for vmap and friends apply.
  1299. * @dmabuf: [in] buffer to vmap
  1300. * @map: [out] returns the vmap pointer
  1301. *
  1302. * This call may fail due to lack of virtual mapping address space.
  1303. * These calls are optional in drivers. The intended use for them
  1304. * is for mapping objects linear in kernel space for high use objects.
  1305. *
  1306. * To ensure coherency users must call dma_buf_begin_cpu_access() and
  1307. * dma_buf_end_cpu_access() around any cpu access performed through this
  1308. * mapping.
  1309. *
  1310. * Returns 0 on success, or a negative errno code otherwise.
  1311. */
  1312. int dma_buf_vmap(struct dma_buf *dmabuf, struct iosys_map *map)
  1313. {
  1314. struct iosys_map ptr;
  1315. int ret = 0;
  1316. iosys_map_clear(map);
  1317. if (WARN_ON(!dmabuf))
  1318. return -EINVAL;
  1319. if (!dmabuf->ops->vmap)
  1320. return -EINVAL;
  1321. mutex_lock(&dmabuf->lock);
  1322. if (dmabuf->vmapping_counter) {
  1323. dmabuf->vmapping_counter++;
  1324. BUG_ON(iosys_map_is_null(&dmabuf->vmap_ptr));
  1325. *map = dmabuf->vmap_ptr;
  1326. goto out_unlock;
  1327. }
  1328. BUG_ON(iosys_map_is_set(&dmabuf->vmap_ptr));
  1329. ret = dmabuf->ops->vmap(dmabuf, &ptr);
  1330. if (WARN_ON_ONCE(ret))
  1331. goto out_unlock;
  1332. dmabuf->vmap_ptr = ptr;
  1333. dmabuf->vmapping_counter = 1;
  1334. *map = dmabuf->vmap_ptr;
  1335. out_unlock:
  1336. mutex_unlock(&dmabuf->lock);
  1337. return ret;
  1338. }
  1339. EXPORT_SYMBOL_NS_GPL(dma_buf_vmap, DMA_BUF);
  1340. /**
  1341. * dma_buf_vunmap - Unmap a vmap obtained by dma_buf_vmap.
  1342. * @dmabuf: [in] buffer to vunmap
  1343. * @map: [in] vmap pointer to vunmap
  1344. */
  1345. void dma_buf_vunmap(struct dma_buf *dmabuf, struct iosys_map *map)
  1346. {
  1347. if (WARN_ON(!dmabuf))
  1348. return;
  1349. BUG_ON(iosys_map_is_null(&dmabuf->vmap_ptr));
  1350. BUG_ON(dmabuf->vmapping_counter == 0);
  1351. BUG_ON(!iosys_map_is_equal(&dmabuf->vmap_ptr, map));
  1352. mutex_lock(&dmabuf->lock);
  1353. if (--dmabuf->vmapping_counter == 0) {
  1354. if (dmabuf->ops->vunmap)
  1355. dmabuf->ops->vunmap(dmabuf, map);
  1356. iosys_map_clear(&dmabuf->vmap_ptr);
  1357. }
  1358. mutex_unlock(&dmabuf->lock);
  1359. }
  1360. EXPORT_SYMBOL_NS_GPL(dma_buf_vunmap, DMA_BUF);
  1361. int dma_buf_get_flags(struct dma_buf *dmabuf, unsigned long *flags)
  1362. {
  1363. int ret = 0;
  1364. if (WARN_ON(!dmabuf) || !flags)
  1365. return -EINVAL;
  1366. if (dmabuf->ops->get_flags)
  1367. ret = dmabuf->ops->get_flags(dmabuf, flags);
  1368. return ret;
  1369. }
  1370. EXPORT_SYMBOL_GPL(dma_buf_get_flags);
  1371. #ifdef CONFIG_DEBUG_FS
  1372. static int dma_buf_debug_show(struct seq_file *s, void *unused)
  1373. {
  1374. struct dma_buf *buf_obj;
  1375. struct dma_buf_attachment *attach_obj;
  1376. int count = 0, attach_count;
  1377. size_t size = 0;
  1378. int ret;
  1379. ret = mutex_lock_interruptible(&db_list.lock);
  1380. if (ret)
  1381. return ret;
  1382. seq_puts(s, "\nDma-buf Objects:\n");
  1383. seq_printf(s, "%-8s\t%-8s\t%-8s\t%-8s\texp_name\t%-8s\tname\n",
  1384. "size", "flags", "mode", "count", "ino");
  1385. list_for_each_entry(buf_obj, &db_list.head, list_node) {
  1386. ret = dma_resv_lock_interruptible(buf_obj->resv, NULL);
  1387. if (ret)
  1388. goto error_unlock;
  1389. spin_lock(&buf_obj->name_lock);
  1390. seq_printf(s, "%08zu\t%08x\t%08x\t%08ld\t%s\t%08lu\t%s\n",
  1391. buf_obj->size,
  1392. buf_obj->file->f_flags, buf_obj->file->f_mode,
  1393. file_count(buf_obj->file),
  1394. buf_obj->exp_name,
  1395. file_inode(buf_obj->file)->i_ino,
  1396. buf_obj->name ?: "<none>");
  1397. spin_unlock(&buf_obj->name_lock);
  1398. dma_resv_describe(buf_obj->resv, s);
  1399. seq_puts(s, "\tAttached Devices:\n");
  1400. attach_count = 0;
  1401. list_for_each_entry(attach_obj, &buf_obj->attachments, node) {
  1402. seq_printf(s, "\t%s\n", dev_name(attach_obj->dev));
  1403. attach_count++;
  1404. }
  1405. dma_resv_unlock(buf_obj->resv);
  1406. seq_printf(s, "Total %d devices attached\n\n",
  1407. attach_count);
  1408. count++;
  1409. size += buf_obj->size;
  1410. }
  1411. seq_printf(s, "\nTotal %d objects, %zu bytes\n", count, size);
  1412. mutex_unlock(&db_list.lock);
  1413. return 0;
  1414. error_unlock:
  1415. mutex_unlock(&db_list.lock);
  1416. return ret;
  1417. }
  1418. DEFINE_SHOW_ATTRIBUTE(dma_buf_debug);
  1419. static struct dentry *dma_buf_debugfs_dir;
  1420. static int dma_buf_init_debugfs(void)
  1421. {
  1422. struct dentry *d;
  1423. int err = 0;
  1424. d = debugfs_create_dir("dma_buf", NULL);
  1425. if (IS_ERR(d))
  1426. return PTR_ERR(d);
  1427. dma_buf_debugfs_dir = d;
  1428. d = debugfs_create_file("bufinfo", S_IRUGO, dma_buf_debugfs_dir,
  1429. NULL, &dma_buf_debug_fops);
  1430. if (IS_ERR(d)) {
  1431. pr_debug("dma_buf: debugfs: failed to create node bufinfo\n");
  1432. debugfs_remove_recursive(dma_buf_debugfs_dir);
  1433. dma_buf_debugfs_dir = NULL;
  1434. err = PTR_ERR(d);
  1435. }
  1436. return err;
  1437. }
  1438. static void dma_buf_uninit_debugfs(void)
  1439. {
  1440. debugfs_remove_recursive(dma_buf_debugfs_dir);
  1441. }
  1442. #else
  1443. static inline int dma_buf_init_debugfs(void)
  1444. {
  1445. return 0;
  1446. }
  1447. static inline void dma_buf_uninit_debugfs(void)
  1448. {
  1449. }
  1450. #endif
  1451. static int __init dma_buf_init(void)
  1452. {
  1453. int ret;
  1454. ret = dma_buf_init_sysfs_statistics();
  1455. if (ret)
  1456. return ret;
  1457. dma_buf_mnt = kern_mount(&dma_buf_fs_type);
  1458. if (IS_ERR(dma_buf_mnt))
  1459. return PTR_ERR(dma_buf_mnt);
  1460. mutex_init(&db_list.lock);
  1461. INIT_LIST_HEAD(&db_list.head);
  1462. dma_buf_init_debugfs();
  1463. return 0;
  1464. }
  1465. subsys_initcall(dma_buf_init);
  1466. static void __exit dma_buf_deinit(void)
  1467. {
  1468. dma_buf_uninit_debugfs();
  1469. kern_unmount(dma_buf_mnt);
  1470. dma_buf_uninit_sysfs_statistics();
  1471. }
  1472. __exitcall(dma_buf_deinit);