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