dma-buf-sharing.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. DMA Buffer Sharing API Guide
  2. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3. Sumit Semwal
  4. <sumit dot semwal at linaro dot org>
  5. <sumit dot semwal at ti dot com>
  6. This document serves as a guide to device-driver writers on what is the dma-buf
  7. buffer sharing API, how to use it for exporting and using shared buffers.
  8. Any device driver which wishes to be a part of DMA buffer sharing, can do so as
  9. either the 'exporter' of buffers, or the 'user' of buffers.
  10. Say a driver A wants to use buffers created by driver B, then we call B as the
  11. exporter, and A as buffer-user.
  12. The exporter
  13. - implements and manages operations[1] for the buffer
  14. - allows other users to share the buffer by using dma_buf sharing APIs,
  15. - manages the details of buffer allocation,
  16. - decides about the actual backing storage where this allocation happens,
  17. - takes care of any migration of scatterlist - for all (shared) users of this
  18. buffer,
  19. The buffer-user
  20. - is one of (many) sharing users of the buffer.
  21. - doesn't need to worry about how the buffer is allocated, or where.
  22. - needs a mechanism to get access to the scatterlist that makes up this buffer
  23. in memory, mapped into its own address space, so it can access the same area
  24. of memory.
  25. dma-buf operations for device dma only
  26. --------------------------------------
  27. The dma_buf buffer sharing API usage contains the following steps:
  28. 1. Exporter announces that it wishes to export a buffer
  29. 2. Userspace gets the file descriptor associated with the exported buffer, and
  30. passes it around to potential buffer-users based on use case
  31. 3. Each buffer-user 'connects' itself to the buffer
  32. 4. When needed, buffer-user requests access to the buffer from exporter
  33. 5. When finished with its use, the buffer-user notifies end-of-DMA to exporter
  34. 6. when buffer-user is done using this buffer completely, it 'disconnects'
  35. itself from the buffer.
  36. 1. Exporter's announcement of buffer export
  37. The buffer exporter announces its wish to export a buffer. In this, it
  38. connects its own private buffer data, provides implementation for operations
  39. that can be performed on the exported dma_buf, and flags for the file
  40. associated with this buffer.
  41. Interface:
  42. struct dma_buf *dma_buf_export_named(void *priv, struct dma_buf_ops *ops,
  43. size_t size, int flags,
  44. const char *exp_name)
  45. If this succeeds, dma_buf_export allocates a dma_buf structure, and returns a
  46. pointer to the same. It also associates an anonymous file with this buffer,
  47. so it can be exported. On failure to allocate the dma_buf object, it returns
  48. NULL.
  49. 'exp_name' is the name of exporter - to facilitate information while
  50. debugging.
  51. Exporting modules which do not wish to provide any specific name may use the
  52. helper define 'dma_buf_export()', with the same arguments as above, but
  53. without the last argument; a __FILE__ pre-processor directive will be
  54. inserted in place of 'exp_name' instead.
  55. 2. Userspace gets a handle to pass around to potential buffer-users
  56. Userspace entity requests for a file-descriptor (fd) which is a handle to the
  57. anonymous file associated with the buffer. It can then share the fd with other
  58. drivers and/or processes.
  59. Interface:
  60. int dma_buf_fd(struct dma_buf *dmabuf)
  61. This API installs an fd for the anonymous file associated with this buffer;
  62. returns either 'fd', or error.
  63. 3. Each buffer-user 'connects' itself to the buffer
  64. Each buffer-user now gets a reference to the buffer, using the fd passed to
  65. it.
  66. Interface:
  67. struct dma_buf *dma_buf_get(int fd)
  68. This API will return a reference to the dma_buf, and increment refcount for
  69. it.
  70. After this, the buffer-user needs to attach its device with the buffer, which
  71. helps the exporter to know of device buffer constraints.
  72. Interface:
  73. struct dma_buf_attachment *dma_buf_attach(struct dma_buf *dmabuf,
  74. struct device *dev)
  75. This API returns reference to an attachment structure, which is then used
  76. for scatterlist operations. It will optionally call the 'attach' dma_buf
  77. operation, if provided by the exporter.
  78. The dma-buf sharing framework does the bookkeeping bits related to managing
  79. the list of all attachments to a buffer.
  80. Until this stage, the buffer-exporter has the option to choose not to actually
  81. allocate the backing storage for this buffer, but wait for the first buffer-user
  82. to request use of buffer for allocation.
  83. 4. When needed, buffer-user requests access to the buffer
  84. Whenever a buffer-user wants to use the buffer for any DMA, it asks for
  85. access to the buffer using dma_buf_map_attachment API. At least one attach to
  86. the buffer must have happened before map_dma_buf can be called.
  87. Interface:
  88. struct sg_table * dma_buf_map_attachment(struct dma_buf_attachment *,
  89. enum dma_data_direction);
  90. This is a wrapper to dma_buf->ops->map_dma_buf operation, which hides the
  91. "dma_buf->ops->" indirection from the users of this interface.
  92. In struct dma_buf_ops, map_dma_buf is defined as
  93. struct sg_table * (*map_dma_buf)(struct dma_buf_attachment *,
  94. enum dma_data_direction);
  95. It is one of the buffer operations that must be implemented by the exporter.
  96. It should return the sg_table containing scatterlist for this buffer, mapped
  97. into caller's address space.
  98. If this is being called for the first time, the exporter can now choose to
  99. scan through the list of attachments for this buffer, collate the requirements
  100. of the attached devices, and choose an appropriate backing storage for the
  101. buffer.
  102. Based on enum dma_data_direction, it might be possible to have multiple users
  103. accessing at the same time (for reading, maybe), or any other kind of sharing
  104. that the exporter might wish to make available to buffer-users.
  105. map_dma_buf() operation can return -EINTR if it is interrupted by a signal.
  106. 5. When finished, the buffer-user notifies end-of-DMA to exporter
  107. Once the DMA for the current buffer-user is over, it signals 'end-of-DMA' to
  108. the exporter using the dma_buf_unmap_attachment API.
  109. Interface:
  110. void dma_buf_unmap_attachment(struct dma_buf_attachment *,
  111. struct sg_table *);
  112. This is a wrapper to dma_buf->ops->unmap_dma_buf() operation, which hides the
  113. "dma_buf->ops->" indirection from the users of this interface.
  114. In struct dma_buf_ops, unmap_dma_buf is defined as
  115. void (*unmap_dma_buf)(struct dma_buf_attachment *, struct sg_table *);
  116. unmap_dma_buf signifies the end-of-DMA for the attachment provided. Like
  117. map_dma_buf, this API also must be implemented by the exporter.
  118. 6. when buffer-user is done using this buffer, it 'disconnects' itself from the
  119. buffer.
  120. After the buffer-user has no more interest in using this buffer, it should
  121. disconnect itself from the buffer:
  122. - it first detaches itself from the buffer.
  123. Interface:
  124. void dma_buf_detach(struct dma_buf *dmabuf,
  125. struct dma_buf_attachment *dmabuf_attach);
  126. This API removes the attachment from the list in dmabuf, and optionally calls
  127. dma_buf->ops->detach(), if provided by exporter, for any housekeeping bits.
  128. - Then, the buffer-user returns the buffer reference to exporter.
  129. Interface:
  130. void dma_buf_put(struct dma_buf *dmabuf);
  131. This API then reduces the refcount for this buffer.
  132. If, as a result of this call, the refcount becomes 0, the 'release' file
  133. operation related to this fd is called. It calls the dmabuf->ops->release()
  134. operation in turn, and frees the memory allocated for dmabuf when exported.
  135. NOTES:
  136. - Importance of attach-detach and {map,unmap}_dma_buf operation pairs
  137. The attach-detach calls allow the exporter to figure out backing-storage
  138. constraints for the currently-interested devices. This allows preferential
  139. allocation, and/or migration of pages across different types of storage
  140. available, if possible.
  141. Bracketing of DMA access with {map,unmap}_dma_buf operations is essential
  142. to allow just-in-time backing of storage, and migration mid-way through a
  143. use-case.
  144. - Migration of backing storage if needed
  145. If after
  146. - at least one map_dma_buf has happened,
  147. - and the backing storage has been allocated for this buffer,
  148. another new buffer-user intends to attach itself to this buffer, it might
  149. be allowed, if possible for the exporter.
  150. In case it is allowed by the exporter:
  151. if the new buffer-user has stricter 'backing-storage constraints', and the
  152. exporter can handle these constraints, the exporter can just stall on the
  153. map_dma_buf until all outstanding access is completed (as signalled by
  154. unmap_dma_buf).
  155. Once all users have finished accessing and have unmapped this buffer, the
  156. exporter could potentially move the buffer to the stricter backing-storage,
  157. and then allow further {map,unmap}_dma_buf operations from any buffer-user
  158. from the migrated backing-storage.
  159. If the exporter cannot fulfil the backing-storage constraints of the new
  160. buffer-user device as requested, dma_buf_attach() would return an error to
  161. denote non-compatibility of the new buffer-sharing request with the current
  162. buffer.
  163. If the exporter chooses not to allow an attach() operation once a
  164. map_dma_buf() API has been called, it simply returns an error.
  165. Kernel cpu access to a dma-buf buffer object
  166. --------------------------------------------
  167. The motivation to allow cpu access from the kernel to a dma-buf object from the
  168. importers side are:
  169. - fallback operations, e.g. if the devices is connected to a usb bus and the
  170. kernel needs to shuffle the data around first before sending it away.
  171. - full transparency for existing users on the importer side, i.e. userspace
  172. should not notice the difference between a normal object from that subsystem
  173. and an imported one backed by a dma-buf. This is really important for drm
  174. opengl drivers that expect to still use all the existing upload/download
  175. paths.
  176. Access to a dma_buf from the kernel context involves three steps:
  177. 1. Prepare access, which invalidate any necessary caches and make the object
  178. available for cpu access.
  179. 2. Access the object page-by-page with the dma_buf map apis
  180. 3. Finish access, which will flush any necessary cpu caches and free reserved
  181. resources.
  182. 1. Prepare access
  183. Before an importer can access a dma_buf object with the cpu from the kernel
  184. context, it needs to notify the exporter of the access that is about to
  185. happen.
  186. Interface:
  187. int dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
  188. size_t start, size_t len,
  189. enum dma_data_direction direction)
  190. This allows the exporter to ensure that the memory is actually available for
  191. cpu access - the exporter might need to allocate or swap-in and pin the
  192. backing storage. The exporter also needs to ensure that cpu access is
  193. coherent for the given range and access direction. The range and access
  194. direction can be used by the exporter to optimize the cache flushing, i.e.
  195. access outside of the range or with a different direction (read instead of
  196. write) might return stale or even bogus data (e.g. when the exporter needs to
  197. copy the data to temporary storage).
  198. This step might fail, e.g. in oom conditions.
  199. 2. Accessing the buffer
  200. To support dma_buf objects residing in highmem cpu access is page-based using
  201. an api similar to kmap. Accessing a dma_buf is done in aligned chunks of
  202. PAGE_SIZE size. Before accessing a chunk it needs to be mapped, which returns
  203. a pointer in kernel virtual address space. Afterwards the chunk needs to be
  204. unmapped again. There is no limit on how often a given chunk can be mapped
  205. and unmapped, i.e. the importer does not need to call begin_cpu_access again
  206. before mapping the same chunk again.
  207. Interfaces:
  208. void *dma_buf_kmap(struct dma_buf *, unsigned long);
  209. void dma_buf_kunmap(struct dma_buf *, unsigned long, void *);
  210. There are also atomic variants of these interfaces. Like for kmap they
  211. facilitate non-blocking fast-paths. Neither the importer nor the exporter (in
  212. the callback) is allowed to block when using these.
  213. Interfaces:
  214. void *dma_buf_kmap_atomic(struct dma_buf *, unsigned long);
  215. void dma_buf_kunmap_atomic(struct dma_buf *, unsigned long, void *);
  216. For importers all the restrictions of using kmap apply, like the limited
  217. supply of kmap_atomic slots. Hence an importer shall only hold onto at most 2
  218. atomic dma_buf kmaps at the same time (in any given process context).
  219. dma_buf kmap calls outside of the range specified in begin_cpu_access are
  220. undefined. If the range is not PAGE_SIZE aligned, kmap needs to succeed on
  221. the partial chunks at the beginning and end but may return stale or bogus
  222. data outside of the range (in these partial chunks).
  223. Note that these calls need to always succeed. The exporter needs to complete
  224. any preparations that might fail in begin_cpu_access.
  225. For some cases the overhead of kmap can be too high, a vmap interface
  226. is introduced. This interface should be used very carefully, as vmalloc
  227. space is a limited resources on many architectures.
  228. Interfaces:
  229. void *dma_buf_vmap(struct dma_buf *dmabuf)
  230. void dma_buf_vunmap(struct dma_buf *dmabuf, void *vaddr)
  231. The vmap call can fail if there is no vmap support in the exporter, or if it
  232. runs out of vmalloc space. Fallback to kmap should be implemented. Note that
  233. the dma-buf layer keeps a reference count for all vmap access and calls down
  234. into the exporter's vmap function only when no vmapping exists, and only
  235. unmaps it once. Protection against concurrent vmap/vunmap calls is provided
  236. by taking the dma_buf->lock mutex.
  237. 3. Finish access
  238. When the importer is done accessing the range specified in begin_cpu_access,
  239. it needs to announce this to the exporter (to facilitate cache flushing and
  240. unpinning of any pinned resources). The result of any dma_buf kmap calls
  241. after end_cpu_access is undefined.
  242. Interface:
  243. void dma_buf_end_cpu_access(struct dma_buf *dma_buf,
  244. size_t start, size_t len,
  245. enum dma_data_direction dir);
  246. Direct Userspace Access/mmap Support
  247. ------------------------------------
  248. Being able to mmap an export dma-buf buffer object has 2 main use-cases:
  249. - CPU fallback processing in a pipeline and
  250. - supporting existing mmap interfaces in importers.
  251. 1. CPU fallback processing in a pipeline
  252. In many processing pipelines it is sometimes required that the cpu can access
  253. the data in a dma-buf (e.g. for thumbnail creation, snapshots, ...). To avoid
  254. the need to handle this specially in userspace frameworks for buffer sharing
  255. it's ideal if the dma_buf fd itself can be used to access the backing storage
  256. from userspace using mmap.
  257. Furthermore Android's ION framework already supports this (and is otherwise
  258. rather similar to dma-buf from a userspace consumer side with using fds as
  259. handles, too). So it's beneficial to support this in a similar fashion on
  260. dma-buf to have a good transition path for existing Android userspace.
  261. No special interfaces, userspace simply calls mmap on the dma-buf fd.
  262. 2. Supporting existing mmap interfaces in exporters
  263. Similar to the motivation for kernel cpu access it is again important that
  264. the userspace code of a given importing subsystem can use the same interfaces
  265. with a imported dma-buf buffer object as with a native buffer object. This is
  266. especially important for drm where the userspace part of contemporary OpenGL,
  267. X, and other drivers is huge, and reworking them to use a different way to
  268. mmap a buffer rather invasive.
  269. The assumption in the current dma-buf interfaces is that redirecting the
  270. initial mmap is all that's needed. A survey of some of the existing
  271. subsystems shows that no driver seems to do any nefarious thing like syncing
  272. up with outstanding asynchronous processing on the device or allocating
  273. special resources at fault time. So hopefully this is good enough, since
  274. adding interfaces to intercept pagefaults and allow pte shootdowns would
  275. increase the complexity quite a bit.
  276. Interface:
  277. int dma_buf_mmap(struct dma_buf *, struct vm_area_struct *,
  278. unsigned long);
  279. If the importing subsystem simply provides a special-purpose mmap call to set
  280. up a mapping in userspace, calling do_mmap with dma_buf->file will equally
  281. achieve that for a dma-buf object.
  282. 3. Implementation notes for exporters
  283. Because dma-buf buffers have invariant size over their lifetime, the dma-buf
  284. core checks whether a vma is too large and rejects such mappings. The
  285. exporter hence does not need to duplicate this check.
  286. Because existing importing subsystems might presume coherent mappings for
  287. userspace, the exporter needs to set up a coherent mapping. If that's not
  288. possible, it needs to fake coherency by manually shooting down ptes when
  289. leaving the cpu domain and flushing caches at fault time. Note that all the
  290. dma_buf files share the same anon inode, hence the exporter needs to replace
  291. the dma_buf file stored in vma->vm_file with it's own if pte shootdown is
  292. required. This is because the kernel uses the underlying inode's address_space
  293. for vma tracking (and hence pte tracking at shootdown time with
  294. unmap_mapping_range).
  295. If the above shootdown dance turns out to be too expensive in certain
  296. scenarios, we can extend dma-buf with a more explicit cache tracking scheme
  297. for userspace mappings. But the current assumption is that using mmap is
  298. always a slower path, so some inefficiencies should be acceptable.
  299. Exporters that shoot down mappings (for any reasons) shall not do any
  300. synchronization at fault time with outstanding device operations.
  301. Synchronization is an orthogonal issue to sharing the backing storage of a
  302. buffer and hence should not be handled by dma-buf itself. This is explicitly
  303. mentioned here because many people seem to want something like this, but if
  304. different exporters handle this differently, buffer sharing can fail in
  305. interesting ways depending upong the exporter (if userspace starts depending
  306. upon this implicit synchronization).
  307. Other Interfaces Exposed to Userspace on the dma-buf FD
  308. ------------------------------------------------------
  309. - Since kernel 3.12 the dma-buf FD supports the llseek system call, but only
  310. with offset=0 and whence=SEEK_END|SEEK_SET. SEEK_SET is supported to allow
  311. the usual size discover pattern size = SEEK_END(0); SEEK_SET(0). Every other
  312. llseek operation will report -EINVAL.
  313. If llseek on dma-buf FDs isn't support the kernel will report -ESPIPE for all
  314. cases. Userspace can use this to detect support for discovering the dma-buf
  315. size using llseek.
  316. Miscellaneous notes
  317. -------------------
  318. - Any exporters or users of the dma-buf buffer sharing framework must have
  319. a 'select DMA_SHARED_BUFFER' in their respective Kconfigs.
  320. - In order to avoid fd leaks on exec, the FD_CLOEXEC flag must be set
  321. on the file descriptor. This is not just a resource leak, but a
  322. potential security hole. It could give the newly exec'd application
  323. access to buffers, via the leaked fd, to which it should otherwise
  324. not be permitted access.
  325. The problem with doing this via a separate fcntl() call, versus doing it
  326. atomically when the fd is created, is that this is inherently racy in a
  327. multi-threaded app[3]. The issue is made worse when it is library code
  328. opening/creating the file descriptor, as the application may not even be
  329. aware of the fd's.
  330. To avoid this problem, userspace must have a way to request O_CLOEXEC
  331. flag be set when the dma-buf fd is created. So any API provided by
  332. the exporting driver to create a dmabuf fd must provide a way to let
  333. userspace control setting of O_CLOEXEC flag passed in to dma_buf_fd().
  334. - If an exporter needs to manually flush caches and hence needs to fake
  335. coherency for mmap support, it needs to be able to zap all the ptes pointing
  336. at the backing storage. Now linux mm needs a struct address_space associated
  337. with the struct file stored in vma->vm_file to do that with the function
  338. unmap_mapping_range. But the dma_buf framework only backs every dma_buf fd
  339. with the anon_file struct file, i.e. all dma_bufs share the same file.
  340. Hence exporters need to setup their own file (and address_space) association
  341. by setting vma->vm_file and adjusting vma->vm_pgoff in the dma_buf mmap
  342. callback. In the specific case of a gem driver the exporter could use the
  343. shmem file already provided by gem (and set vm_pgoff = 0). Exporters can then
  344. zap ptes by unmapping the corresponding range of the struct address_space
  345. associated with their own file.
  346. References:
  347. [1] struct dma_buf_ops in include/linux/dma-buf.h
  348. [2] All interfaces mentioned above defined in include/linux/dma-buf.h
  349. [3] https://lwn.net/Articles/236486/