dma-buf.c 47 KB

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