Back to home page

LXR

 
 

    


0001                     DMA Buffer Sharing API Guide
0002                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0003 
0004                             Sumit Semwal
0005                 <sumit dot semwal at linaro dot org>
0006                  <sumit dot semwal at ti dot com>
0007 
0008 This document serves as a guide to device-driver writers on what is the dma-buf
0009 buffer sharing API, how to use it for exporting and using shared buffers.
0010 
0011 Any device driver which wishes to be a part of DMA buffer sharing, can do so as
0012 either the 'exporter' of buffers, or the 'user' of buffers.
0013 
0014 Say a driver A wants to use buffers created by driver B, then we call B as the
0015 exporter, and A as buffer-user.
0016 
0017 The exporter
0018 - implements and manages operations[1] for the buffer
0019 - allows other users to share the buffer by using dma_buf sharing APIs,
0020 - manages the details of buffer allocation,
0021 - decides about the actual backing storage where this allocation happens,
0022 - takes care of any migration of scatterlist - for all (shared) users of this
0023    buffer,
0024 
0025 The buffer-user
0026 - is one of (many) sharing users of the buffer.
0027 - doesn't need to worry about how the buffer is allocated, or where.
0028 - needs a mechanism to get access to the scatterlist that makes up this buffer
0029    in memory, mapped into its own address space, so it can access the same area
0030    of memory.
0031 
0032 dma-buf operations for device dma only
0033 --------------------------------------
0034 
0035 The dma_buf buffer sharing API usage contains the following steps:
0036 
0037 1. Exporter announces that it wishes to export a buffer
0038 2. Userspace gets the file descriptor associated with the exported buffer, and
0039    passes it around to potential buffer-users based on use case
0040 3. Each buffer-user 'connects' itself to the buffer
0041 4. When needed, buffer-user requests access to the buffer from exporter
0042 5. When finished with its use, the buffer-user notifies end-of-DMA to exporter
0043 6. when buffer-user is done using this buffer completely, it 'disconnects'
0044    itself from the buffer.
0045 
0046 
0047 1. Exporter's announcement of buffer export
0048 
0049    The buffer exporter announces its wish to export a buffer. In this, it
0050    connects its own private buffer data, provides implementation for operations
0051    that can be performed on the exported dma_buf, and flags for the file
0052    associated with this buffer. All these fields are filled in struct
0053    dma_buf_export_info, defined via the DEFINE_DMA_BUF_EXPORT_INFO macro.
0054 
0055    Interface:
0056       DEFINE_DMA_BUF_EXPORT_INFO(exp_info)
0057       struct dma_buf *dma_buf_export(struct dma_buf_export_info *exp_info)
0058 
0059    If this succeeds, dma_buf_export allocates a dma_buf structure, and
0060    returns a pointer to the same. It also associates an anonymous file with this
0061    buffer, so it can be exported. On failure to allocate the dma_buf object,
0062    it returns NULL.
0063 
0064    'exp_name' in struct dma_buf_export_info is the name of exporter - to
0065    facilitate information while debugging. It is set to KBUILD_MODNAME by
0066    default, so exporters don't have to provide a specific name, if they don't
0067    wish to.
0068 
0069    DEFINE_DMA_BUF_EXPORT_INFO macro defines the struct dma_buf_export_info,
0070    zeroes it out and pre-populates exp_name in it.
0071 
0072 
0073 2. Userspace gets a handle to pass around to potential buffer-users
0074 
0075    Userspace entity requests for a file-descriptor (fd) which is a handle to the
0076    anonymous file associated with the buffer. It can then share the fd with other
0077    drivers and/or processes.
0078 
0079    Interface:
0080       int dma_buf_fd(struct dma_buf *dmabuf, int flags)
0081 
0082    This API installs an fd for the anonymous file associated with this buffer;
0083    returns either 'fd', or error.
0084 
0085 3. Each buffer-user 'connects' itself to the buffer
0086 
0087    Each buffer-user now gets a reference to the buffer, using the fd passed to
0088    it.
0089 
0090    Interface:
0091       struct dma_buf *dma_buf_get(int fd)
0092 
0093    This API will return a reference to the dma_buf, and increment refcount for
0094    it.
0095 
0096    After this, the buffer-user needs to attach its device with the buffer, which
0097    helps the exporter to know of device buffer constraints.
0098 
0099    Interface:
0100       struct dma_buf_attachment *dma_buf_attach(struct dma_buf *dmabuf,
0101                                                 struct device *dev)
0102 
0103    This API returns reference to an attachment structure, which is then used
0104    for scatterlist operations. It will optionally call the 'attach' dma_buf
0105    operation, if provided by the exporter.
0106 
0107    The dma-buf sharing framework does the bookkeeping bits related to managing
0108    the list of all attachments to a buffer.
0109 
0110 Until this stage, the buffer-exporter has the option to choose not to actually
0111 allocate the backing storage for this buffer, but wait for the first buffer-user
0112 to request use of buffer for allocation.
0113 
0114 
0115 4. When needed, buffer-user requests access to the buffer
0116 
0117    Whenever a buffer-user wants to use the buffer for any DMA, it asks for
0118    access to the buffer using dma_buf_map_attachment API. At least one attach to
0119    the buffer must have happened before map_dma_buf can be called.
0120 
0121    Interface:
0122       struct sg_table * dma_buf_map_attachment(struct dma_buf_attachment *,
0123                                          enum dma_data_direction);
0124 
0125    This is a wrapper to dma_buf->ops->map_dma_buf operation, which hides the
0126    "dma_buf->ops->" indirection from the users of this interface.
0127 
0128    In struct dma_buf_ops, map_dma_buf is defined as
0129       struct sg_table * (*map_dma_buf)(struct dma_buf_attachment *,
0130                                                 enum dma_data_direction);
0131 
0132    It is one of the buffer operations that must be implemented by the exporter.
0133    It should return the sg_table containing scatterlist for this buffer, mapped
0134    into caller's address space.
0135 
0136    If this is being called for the first time, the exporter can now choose to
0137    scan through the list of attachments for this buffer, collate the requirements
0138    of the attached devices, and choose an appropriate backing storage for the
0139    buffer.
0140 
0141    Based on enum dma_data_direction, it might be possible to have multiple users
0142    accessing at the same time (for reading, maybe), or any other kind of sharing
0143    that the exporter might wish to make available to buffer-users.
0144 
0145    map_dma_buf() operation can return -EINTR if it is interrupted by a signal.
0146 
0147 
0148 5. When finished, the buffer-user notifies end-of-DMA to exporter
0149 
0150    Once the DMA for the current buffer-user is over, it signals 'end-of-DMA' to
0151    the exporter using the dma_buf_unmap_attachment API.
0152 
0153    Interface:
0154       void dma_buf_unmap_attachment(struct dma_buf_attachment *,
0155                                     struct sg_table *);
0156 
0157    This is a wrapper to dma_buf->ops->unmap_dma_buf() operation, which hides the
0158    "dma_buf->ops->" indirection from the users of this interface.
0159 
0160    In struct dma_buf_ops, unmap_dma_buf is defined as
0161       void (*unmap_dma_buf)(struct dma_buf_attachment *,
0162                             struct sg_table *,
0163                             enum dma_data_direction);
0164 
0165    unmap_dma_buf signifies the end-of-DMA for the attachment provided. Like
0166    map_dma_buf, this API also must be implemented by the exporter.
0167 
0168 
0169 6. when buffer-user is done using this buffer, it 'disconnects' itself from the
0170    buffer.
0171 
0172    After the buffer-user has no more interest in using this buffer, it should
0173    disconnect itself from the buffer:
0174 
0175    - it first detaches itself from the buffer.
0176 
0177    Interface:
0178       void dma_buf_detach(struct dma_buf *dmabuf,
0179                           struct dma_buf_attachment *dmabuf_attach);
0180 
0181    This API removes the attachment from the list in dmabuf, and optionally calls
0182    dma_buf->ops->detach(), if provided by exporter, for any housekeeping bits.
0183 
0184    - Then, the buffer-user returns the buffer reference to exporter.
0185 
0186    Interface:
0187      void dma_buf_put(struct dma_buf *dmabuf);
0188 
0189    This API then reduces the refcount for this buffer.
0190 
0191    If, as a result of this call, the refcount becomes 0, the 'release' file
0192    operation related to this fd is called. It calls the dmabuf->ops->release()
0193    operation in turn, and frees the memory allocated for dmabuf when exported.
0194 
0195 NOTES:
0196 - Importance of attach-detach and {map,unmap}_dma_buf operation pairs
0197    The attach-detach calls allow the exporter to figure out backing-storage
0198    constraints for the currently-interested devices. This allows preferential
0199    allocation, and/or migration of pages across different types of storage
0200    available, if possible.
0201 
0202    Bracketing of DMA access with {map,unmap}_dma_buf operations is essential
0203    to allow just-in-time backing of storage, and migration mid-way through a
0204    use-case.
0205 
0206 - Migration of backing storage if needed
0207    If after
0208    - at least one map_dma_buf has happened,
0209    - and the backing storage has been allocated for this buffer,
0210    another new buffer-user intends to attach itself to this buffer, it might
0211    be allowed, if possible for the exporter.
0212 
0213    In case it is allowed by the exporter:
0214     if the new buffer-user has stricter 'backing-storage constraints', and the
0215     exporter can handle these constraints, the exporter can just stall on the
0216     map_dma_buf until all outstanding access is completed (as signalled by
0217     unmap_dma_buf).
0218     Once all users have finished accessing and have unmapped this buffer, the
0219     exporter could potentially move the buffer to the stricter backing-storage,
0220     and then allow further {map,unmap}_dma_buf operations from any buffer-user
0221     from the migrated backing-storage.
0222 
0223    If the exporter cannot fulfill the backing-storage constraints of the new
0224    buffer-user device as requested, dma_buf_attach() would return an error to
0225    denote non-compatibility of the new buffer-sharing request with the current
0226    buffer.
0227 
0228    If the exporter chooses not to allow an attach() operation once a
0229    map_dma_buf() API has been called, it simply returns an error.
0230 
0231 Kernel cpu access to a dma-buf buffer object
0232 --------------------------------------------
0233 
0234 The motivation to allow cpu access from the kernel to a dma-buf object from the
0235 importers side are:
0236 - fallback operations, e.g. if the devices is connected to a usb bus and the
0237   kernel needs to shuffle the data around first before sending it away.
0238 - full transparency for existing users on the importer side, i.e. userspace
0239   should not notice the difference between a normal object from that subsystem
0240   and an imported one backed by a dma-buf. This is really important for drm
0241   opengl drivers that expect to still use all the existing upload/download
0242   paths.
0243 
0244 Access to a dma_buf from the kernel context involves three steps:
0245 
0246 1. Prepare access, which invalidate any necessary caches and make the object
0247    available for cpu access.
0248 2. Access the object page-by-page with the dma_buf map apis
0249 3. Finish access, which will flush any necessary cpu caches and free reserved
0250    resources.
0251 
0252 1. Prepare access
0253 
0254    Before an importer can access a dma_buf object with the cpu from the kernel
0255    context, it needs to notify the exporter of the access that is about to
0256    happen.
0257 
0258    Interface:
0259       int dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
0260                                    enum dma_data_direction direction)
0261 
0262    This allows the exporter to ensure that the memory is actually available for
0263    cpu access - the exporter might need to allocate or swap-in and pin the
0264    backing storage. The exporter also needs to ensure that cpu access is
0265    coherent for the access direction. The direction can be used by the exporter
0266    to optimize the cache flushing, i.e. access with a different direction (read
0267    instead of write) might return stale or even bogus data (e.g. when the
0268    exporter needs to copy the data to temporary storage).
0269 
0270    This step might fail, e.g. in oom conditions.
0271 
0272 2. Accessing the buffer
0273 
0274    To support dma_buf objects residing in highmem cpu access is page-based using
0275    an api similar to kmap. Accessing a dma_buf is done in aligned chunks of
0276    PAGE_SIZE size. Before accessing a chunk it needs to be mapped, which returns
0277    a pointer in kernel virtual address space. Afterwards the chunk needs to be
0278    unmapped again. There is no limit on how often a given chunk can be mapped
0279    and unmapped, i.e. the importer does not need to call begin_cpu_access again
0280    before mapping the same chunk again.
0281 
0282    Interfaces:
0283       void *dma_buf_kmap(struct dma_buf *, unsigned long);
0284       void dma_buf_kunmap(struct dma_buf *, unsigned long, void *);
0285 
0286    There are also atomic variants of these interfaces. Like for kmap they
0287    facilitate non-blocking fast-paths. Neither the importer nor the exporter (in
0288    the callback) is allowed to block when using these.
0289 
0290    Interfaces:
0291       void *dma_buf_kmap_atomic(struct dma_buf *, unsigned long);
0292       void dma_buf_kunmap_atomic(struct dma_buf *, unsigned long, void *);
0293 
0294    For importers all the restrictions of using kmap apply, like the limited
0295    supply of kmap_atomic slots. Hence an importer shall only hold onto at most 2
0296    atomic dma_buf kmaps at the same time (in any given process context).
0297 
0298    dma_buf kmap calls outside of the range specified in begin_cpu_access are
0299    undefined. If the range is not PAGE_SIZE aligned, kmap needs to succeed on
0300    the partial chunks at the beginning and end but may return stale or bogus
0301    data outside of the range (in these partial chunks).
0302 
0303    Note that these calls need to always succeed. The exporter needs to complete
0304    any preparations that might fail in begin_cpu_access.
0305 
0306    For some cases the overhead of kmap can be too high, a vmap interface
0307    is introduced. This interface should be used very carefully, as vmalloc
0308    space is a limited resources on many architectures.
0309 
0310    Interfaces:
0311       void *dma_buf_vmap(struct dma_buf *dmabuf)
0312       void dma_buf_vunmap(struct dma_buf *dmabuf, void *vaddr)
0313 
0314    The vmap call can fail if there is no vmap support in the exporter, or if it
0315    runs out of vmalloc space. Fallback to kmap should be implemented. Note that
0316    the dma-buf layer keeps a reference count for all vmap access and calls down
0317    into the exporter's vmap function only when no vmapping exists, and only
0318    unmaps it once. Protection against concurrent vmap/vunmap calls is provided
0319    by taking the dma_buf->lock mutex.
0320 
0321 3. Finish access
0322 
0323    When the importer is done accessing the CPU, it needs to announce this to
0324    the exporter (to facilitate cache flushing and unpinning of any pinned
0325    resources). The result of any dma_buf kmap calls after end_cpu_access is
0326    undefined.
0327 
0328    Interface:
0329       void dma_buf_end_cpu_access(struct dma_buf *dma_buf,
0330                                   enum dma_data_direction dir);
0331 
0332 
0333 Direct Userspace Access/mmap Support
0334 ------------------------------------
0335 
0336 Being able to mmap an export dma-buf buffer object has 2 main use-cases:
0337 - CPU fallback processing in a pipeline and
0338 - supporting existing mmap interfaces in importers.
0339 
0340 1. CPU fallback processing in a pipeline
0341 
0342    In many processing pipelines it is sometimes required that the cpu can access
0343    the data in a dma-buf (e.g. for thumbnail creation, snapshots, ...). To avoid
0344    the need to handle this specially in userspace frameworks for buffer sharing
0345    it's ideal if the dma_buf fd itself can be used to access the backing storage
0346    from userspace using mmap.
0347 
0348    Furthermore Android's ION framework already supports this (and is otherwise
0349    rather similar to dma-buf from a userspace consumer side with using fds as
0350    handles, too). So it's beneficial to support this in a similar fashion on
0351    dma-buf to have a good transition path for existing Android userspace.
0352 
0353    No special interfaces, userspace simply calls mmap on the dma-buf fd, making
0354    sure that the cache synchronization ioctl (DMA_BUF_IOCTL_SYNC) is *always*
0355    used when the access happens. Note that DMA_BUF_IOCTL_SYNC can fail with
0356    -EAGAIN or -EINTR, in which case it must be restarted.
0357 
0358    Some systems might need some sort of cache coherency management e.g. when
0359    CPU and GPU domains are being accessed through dma-buf at the same time. To
0360    circumvent this problem there are begin/end coherency markers, that forward
0361    directly to existing dma-buf device drivers vfunc hooks. Userspace can make
0362    use of those markers through the DMA_BUF_IOCTL_SYNC ioctl. The sequence
0363    would be used like following:
0364      - mmap dma-buf fd
0365      - for each drawing/upload cycle in CPU 1. SYNC_START ioctl, 2. read/write
0366        to mmap area 3. SYNC_END ioctl. This can be repeated as often as you
0367        want (with the new data being consumed by the GPU or say scanout device)
0368      - munmap once you don't need the buffer any more
0369 
0370     For correctness and optimal performance, it is always required to use
0371     SYNC_START and SYNC_END before and after, respectively, when accessing the
0372     mapped address. Userspace cannot rely on coherent access, even when there
0373     are systems where it just works without calling these ioctls.
0374 
0375 2. Supporting existing mmap interfaces in importers
0376 
0377    Similar to the motivation for kernel cpu access it is again important that
0378    the userspace code of a given importing subsystem can use the same interfaces
0379    with a imported dma-buf buffer object as with a native buffer object. This is
0380    especially important for drm where the userspace part of contemporary OpenGL,
0381    X, and other drivers is huge, and reworking them to use a different way to
0382    mmap a buffer rather invasive.
0383 
0384    The assumption in the current dma-buf interfaces is that redirecting the
0385    initial mmap is all that's needed. A survey of some of the existing
0386    subsystems shows that no driver seems to do any nefarious thing like syncing
0387    up with outstanding asynchronous processing on the device or allocating
0388    special resources at fault time. So hopefully this is good enough, since
0389    adding interfaces to intercept pagefaults and allow pte shootdowns would
0390    increase the complexity quite a bit.
0391 
0392    Interface:
0393       int dma_buf_mmap(struct dma_buf *, struct vm_area_struct *,
0394                        unsigned long);
0395 
0396    If the importing subsystem simply provides a special-purpose mmap call to set
0397    up a mapping in userspace, calling do_mmap with dma_buf->file will equally
0398    achieve that for a dma-buf object.
0399 
0400 3. Implementation notes for exporters
0401 
0402    Because dma-buf buffers have invariant size over their lifetime, the dma-buf
0403    core checks whether a vma is too large and rejects such mappings. The
0404    exporter hence does not need to duplicate this check.
0405 
0406    Because existing importing subsystems might presume coherent mappings for
0407    userspace, the exporter needs to set up a coherent mapping. If that's not
0408    possible, it needs to fake coherency by manually shooting down ptes when
0409    leaving the cpu domain and flushing caches at fault time. Note that all the
0410    dma_buf files share the same anon inode, hence the exporter needs to replace
0411    the dma_buf file stored in vma->vm_file with it's own if pte shootdown is
0412    required. This is because the kernel uses the underlying inode's address_space
0413    for vma tracking (and hence pte tracking at shootdown time with
0414    unmap_mapping_range).
0415 
0416    If the above shootdown dance turns out to be too expensive in certain
0417    scenarios, we can extend dma-buf with a more explicit cache tracking scheme
0418    for userspace mappings. But the current assumption is that using mmap is
0419    always a slower path, so some inefficiencies should be acceptable.
0420 
0421    Exporters that shoot down mappings (for any reasons) shall not do any
0422    synchronization at fault time with outstanding device operations.
0423    Synchronization is an orthogonal issue to sharing the backing storage of a
0424    buffer and hence should not be handled by dma-buf itself. This is explicitly
0425    mentioned here because many people seem to want something like this, but if
0426    different exporters handle this differently, buffer sharing can fail in
0427    interesting ways depending upong the exporter (if userspace starts depending
0428    upon this implicit synchronization).
0429 
0430 Other Interfaces Exposed to Userspace on the dma-buf FD
0431 ------------------------------------------------------
0432 
0433 - Since kernel 3.12 the dma-buf FD supports the llseek system call, but only
0434   with offset=0 and whence=SEEK_END|SEEK_SET. SEEK_SET is supported to allow
0435   the usual size discover pattern size = SEEK_END(0); SEEK_SET(0). Every other
0436   llseek operation will report -EINVAL.
0437 
0438   If llseek on dma-buf FDs isn't support the kernel will report -ESPIPE for all
0439   cases. Userspace can use this to detect support for discovering the dma-buf
0440   size using llseek.
0441 
0442 Miscellaneous notes
0443 -------------------
0444 
0445 - Any exporters or users of the dma-buf buffer sharing framework must have
0446   a 'select DMA_SHARED_BUFFER' in their respective Kconfigs.
0447 
0448 - In order to avoid fd leaks on exec, the FD_CLOEXEC flag must be set
0449   on the file descriptor.  This is not just a resource leak, but a
0450   potential security hole.  It could give the newly exec'd application
0451   access to buffers, via the leaked fd, to which it should otherwise
0452   not be permitted access.
0453 
0454   The problem with doing this via a separate fcntl() call, versus doing it
0455   atomically when the fd is created, is that this is inherently racy in a
0456   multi-threaded app[3].  The issue is made worse when it is library code
0457   opening/creating the file descriptor, as the application may not even be
0458   aware of the fd's.
0459 
0460   To avoid this problem, userspace must have a way to request O_CLOEXEC
0461   flag be set when the dma-buf fd is created.  So any API provided by
0462   the exporting driver to create a dmabuf fd must provide a way to let
0463   userspace control setting of O_CLOEXEC flag passed in to dma_buf_fd().
0464 
0465 - If an exporter needs to manually flush caches and hence needs to fake
0466   coherency for mmap support, it needs to be able to zap all the ptes pointing
0467   at the backing storage. Now linux mm needs a struct address_space associated
0468   with the struct file stored in vma->vm_file to do that with the function
0469   unmap_mapping_range. But the dma_buf framework only backs every dma_buf fd
0470   with the anon_file struct file, i.e. all dma_bufs share the same file.
0471 
0472   Hence exporters need to setup their own file (and address_space) association
0473   by setting vma->vm_file and adjusting vma->vm_pgoff in the dma_buf mmap
0474   callback. In the specific case of a gem driver the exporter could use the
0475   shmem file already provided by gem (and set vm_pgoff = 0). Exporters can then
0476   zap ptes by unmapping the corresponding range of the struct address_space
0477   associated with their own file.
0478 
0479 References:
0480 [1] struct dma_buf_ops in include/linux/dma-buf.h
0481 [2] All interfaces mentioned above defined in include/linux/dma-buf.h
0482 [3] https://lwn.net/Articles/236486/