BUS_DMA(9)
π BUS_DMA(9): Bus and Machine Independent DMA Mapping Interface
okay bestie, welcome to BUS_DMA(9) from the Kernel Developer's Manual β the page where the kernel gets its whole DMA mapping situation together. It's giving foundational lore, and every function name and prototype is here, so you can read it like the group chat receipts. π
πΈ NAME πΈ
The whole fam on this page: bus_dma, bus_dma_tag_create, bus_dma_tag_destroy, bus_dma_template_init, bus_dma_template_tag, bus_dma_template_clone, bus_dma_template_fill, BUS_DMA_TEMPLATE_FILL, bus_dmamap_create, bus_dmamap_destroy, bus_dmamap_load, bus_dmamap_load_bio, bus_dmamap_load_ccb, bus_dmamap_load_crp, bus_dmamap_load_crp_buffer, bus_dmamap_load_mbuf, bus_dmamap_load_mbuf_sg, bus_dmamap_load_uio, bus_dmamap_unload, bus_dmamap_sync, bus_dmamem_alloc, bus_dmamem_free β all together, they're the Bus and Machine Independent DMA Mapping Interface. Yes, the whole squad. β¨
β¨ SYNOPSIS β¨
Include this header, then here are all the prototypes, no cap:
#include <machine/bus.h>
int
bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
bus_addr_t boundary, bus_addr_t lowaddr, bus_addr_t highaddr,
bus_dma_filter_t *filtfunc, void *filtfuncarg, bus_size_t maxsize,
int nsegments, bus_size_t maxsegsz, int flags,
bus_dma_lock_t *lockfunc, void *lockfuncarg, bus_dma_tag_t *dmat);
int
bus_dma_tag_destroy(bus_dma_tag_t dmat);
void
bus_dma_template_init(bus_dma_template_t *template,
bus_dma_tag_t parent);
int
bus_dma_template_tag(bus_dma_template_t *template, bus_dma_tag_t *dmat);
void
bus_dma_template_clone(bus_dma_template_t *template,
bus_dma_tag_t dmat);
void
bus_dma_template_fill(bus_dma_template_t *template,
bus_dma_param_t params[], u_int count);
BUS_DMA_TEMPLATE_FILL(bus_dma_template_t *template,
bus_dma_param_t param ...);
int
bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp);
int
bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map);
int
bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
bus_size_t buflen, bus_dmamap_callback_t *callback,
void *callback_arg, int flags);
int
bus_dmamap_load_bio(bus_dma_tag_t dmat, bus_dmamap_t map,
struct bio *bio, bus_dmamap_callback_t *callback,
void *callback_arg, int flags);
int
bus_dmamap_load_ccb(bus_dma_tag_t dmat, bus_dmamap_t map,
union ccb *ccb, bus_dmamap_callback_t *callback, void *callback_arg,
int flags);
int
bus_dmamap_load_crp(bus_dma_tag_t dmat, bus_dmamap_t map,
struct crypto *crp, bus_dmamap_callback_t *callback,
void *callback_arg, int flags);
int
bus_dmamap_load_crp_buffer(bus_dma_tag_t dmat, bus_dmamap_t map,
struct crypto_buffer *cb, bus_dmamap_callback_t *callback,
void *callback_arg, int flags);
int
bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map,
struct mbuf *mbuf, bus_dmamap_callback2_t *callback,
void *callback_arg, int flags);
int
bus_dmamap_load_mbuf_sg(bus_dma_tag_t dmat, bus_dmamap_t map,
struct mbuf *mbuf, bus_dma_segment_t *segs, int *nsegs, int flags);
int
bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
struct uio *uio, bus_dmamap_callback2_t *callback,
void *callback_arg, int flags);
void
bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map);
void
bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, op);
int
bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
bus_dmamap_t *mapp);
void
bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map);
π¦ DESCRIPTION π¦
Direct Memory Access (DMA) is a method of transferring data without involving the CPU, thus providing higher performance. Highkey slay. A DMA transaction can be achieved between device to memory, device to device, or memory to memory. π«
The bus_dma API is a bus, device, and machine-independent (MI) interface to DMA mechanisms. It provides the client with flexibility and simplicity by abstracting machine dependent issues like setting up DMA mappings, handling cache issues, bus specific features and limitations. It's the "don't worry about the weird machine bits, bestie" layer. π«Ά
π OVERVIEW π
A tag structure (bus_dma_tag_t) is used to describe the properties of a group of related DMA transactions. One way to view this is that a tag describes the limitations of a DMA engine. For example, if a DMA engine in a device is limited to 32-bit addresses, that limitation is specified by a parameter when creating the tag for that device. Similarly, a tag can be marked as requiring buffers whose addresses are aligned to a specific boundary. Vibe check: the tag is the rulebook. π
Some devices may require multiple tags to describe DMA transactions with differing properties. For example, a device might require 16-byte alignment of its descriptor ring while permitting arbitrary alignment of I/O buffers. In this case, the driver must create one tag for the descriptor ring and a separate tag for I/O buffers. If a device has restrictions that are common to all DMA transactions in addition to restrictions that differ between unrelated groups of transactions, the driver can first create a βparentβ tag that describes the common restrictions. The per-group tags can then inherit these restrictions from this βparentβ tag rather than having to list them explicitly when creating the per-group tags. It's giving "family plan for restrictions." π
A mapping structure (bus_dmamap_t) represents a mapping of a memory region for DMA. On systems with I/O MMUs, the mapping structure tracks any I/O MMU entries used by a request. For DMA requests that require bounce pages, the mapping tracks the bounce pages used. The mapping is literally keeping receipts for what the request is using. π§Ύ
To prepare for one or more DMA transactions, a mapping must be bound to a memory region by calling one of the bus_dmamap_load() functions. These functions configure the mapping which can include programming entries in an I/O MMU and/or allocating bounce pages. An output of these functions (either directly or indirectly by invoking a callback routine) is the list of scatter/gather address ranges a consumer can pass to a DMA engine to access the memory region. When a mapping is no longer needed, the mapping must be unloaded via bus_dmamap_unload(). No lingering attachments, bestie. π«
Before and after each DMA transaction, bus_dmamap_sync() must be used to ensure that the correct data is used by the DMA engine and the CPU. If a mapping uses bounce pages, the sync operations copy data between the bounce pages and the memory region bound to the mapping. Sync operations also handle architecture-specific details such as CPU cache flushing and CPU memory operation ordering. It's the "make sure everyone's seeing the same data" step. π₯
π STATIC VS DYNAMIC π
bus_dma handles two types of DMA transactions: static and dynamic. Static transactions are used with a long-lived memory region that is reused for many transactions such as a descriptor ring. Dynamic transactions are used for transfers to or from transient buffers such as I/O buffers holding a network packet or disk block. Each transaction type uses a different subset of the bus_dma API. Two flavors, two vibes. π
π Static Transactions π
Static transactions use memory regions allocated by bus_dma. Each static memory region is allocated by calling bus_dmamem_alloc(). This function requires a valid tag describing the properties of the DMA transactions to this region such as alignment or address restrictions. Multiple regions can share a single tag if they share the same restrictions. Iconic sharing behavior. π«Ά
bus_dmamem_alloc() allocates a memory region along with a mapping object. The associated tag, memory region, and mapping object must then be passed to bus_dmamap_load() to bind the mapping to the allocated region and obtain the scatter/gather list.
It is expected that bus_dmamem_alloc() will attempt to allocate memory requiring less expensive sync operations (for example, implementations should not allocate regions requiring bounce pages), but sync operations should still be used. For example, a driver should use bus_dmamap_sync() in an interrupt handler before reading descriptor ring entries written by the device prior to the interrupt. Lowkey still do the sync, even when it's supposed to be easy. π
When a consumer is finished with a memory region, it should unload the mapping via bus_dmamap_unload() and then release the memory region and mapping object via bus_dmamem_free(). Cleanup era. π§Ή
π§ Dynamic Transactions π§
Dynamic transactions map memory regions provided by other parts of the system. A tag must be created via bus_dma_tag_create() to describe the DMA transactions to and from these memory regions, and a pool of mapping objects must be allocated via bus_dmamap_create() to track the mappings of any in-flight transactions. Pool party, but for mappings. π
When a consumer wishes to schedule a transaction for a memory region, the consumer must first obtain an unused mapping object from its pool of mapping objects. The memory region must be bound to the mapping object via one of the bus_dmamap_load() functions. Before scheduling the transaction, the consumer should sync the memory region via bus_dmamap_sync() with one or more of the βPREβ flags. After the transaction has completed, the consumer should sync the memory region via bus_dmamap_sync() with one or more of the βPOSTβ flags. The mapping can then be unloaded via bus_dmamap_unload(), and the mapping object can be returned to the pool of unused mapping objects. PRE then POST, in that order. Periodt. π
When a consumer is no longer scheduling DMA transactions, the mapping objects should be freed via bus_dmamap_destroy(), and the tag should be freed via bus_dma_tag_destroy(). That's the full lifecycle, and it ate. π₯
πΈ STRUCTURES AND TYPES πΈ
bus_dma_tag_t π·οΈ
okay so a bus_dma_tag_t is a machine-dependent (MD) opaque type that describes the characteristics of a group of DMA transactions. DMA tags are organized into a hierarchy, with each child tag inheriting the restrictions of its parent. This lets all devices along the path of DMA transactions contribute to the constraints of those transactions. iconic hierarchy behavior, honestly π
bus_dma_template_t π§©
A template is a structure for creating a bus_dma_tag_t from a set of defaults. Once initialized with bus_dma_template_init(), a driver can over-ride individual fields to suit its needs. The following fields start with the indicated default values:
alignmentβ1boundaryβ0lowaddrβBUS_SPACE_MAXADDRhighaddrβBUS_SPACE_MAXADDRmaxsizeβBUS_SPACE_MAXSIZEnsegmentsβBUS_SPACE_UNRESTRICTEDmaxsegsizeβBUS_SPACE_MAXSIZEflagsβ0lockfuncβNULLlockfuncargβNULL
Descriptions of each field are documented with bus_dma_tag_create(). Note that the filtfunc and filtfuncarg attributes of the DMA tag are not supported with templates. π«Ά
bus_dma_filter_t π΅οΈ
Client specified address filter having the format:
int client_filter(void *filtarg, bus_addr_t testaddr)
Address filters can be specified during tag creation to allow for devices whose DMA address restrictions cannot be specified by a single window. The filtarg argument is specified by the client during tag creation to be passed to all invocations of the callback. The testaddr argument contains a potential starting address of a DMA mapping. The filter function operates on the set of addresses from testaddr to trunc_page(testaddr) + PAGE_SIZE - 1, inclusive. The filter function should return zero if any mapping in this range can be accommodated by the device and non-zero otherwise.
Note: the use of filters is no longer supported and will result in an error. π
bus_dma_segment_t π§±
A machine-dependent type that describes individual DMA segments. It contains the following fields:
bus_addr_t ds_addr;
bus_size_t ds_len;
The ds_addr field contains the device visible address of the DMA segment, and ds_len contains the length of the DMA segment. Although the DMA segments returned by a mapping call will adhere to all restrictions necessary for a successful DMA operation, some conversion (e.g. a conversion from host byte order to the device's byte order) is almost always required when presenting segment information to the device. literally always check your byte order, bestie π¦
bus_dmamap_t πΊοΈ
A machine-dependent opaque type describing an individual mapping. One map is used for each memory allocation that will be loaded. Maps can be reused once they have been unloaded. Multiple maps can be associated with one DMA tag. While the value of the map may evaluate to NULL on some platforms under certain conditions, it should never be assumed that it will be NULL in all cases. do not manifest a NULL-safe map, okay? π
bus_dmamap_callback_t π
Client specified callback for receiving mapping information resulting from the load of a bus_dmamap_t via bus_dmamap_load(), bus_dmamap_load_bio(), bus_dmamap_load_ccb(), bus_dmamap_load_crp(), or bus_dmamap_load_crp_buffer(). Callbacks are of the format:
void client_callback(void *callback_arg, bus_dma_segment_t
*segs, int nseg, int error)
The callback_arg is the callback argument passed to dmamap load functions. The segs and nseg arguments describe an array of bus_dma_segment_t structures that represent the mapping. This array is only valid within the scope of the callback function. The success or failure of the mapping is indicated by the error argument. More information on the use of callbacks can be found in the description of the individual dmamap load functions. π
bus_dmamap_callback2_t πβ¨
Client specified callback for receiving mapping information resulting from the load of a bus_dmamap_t via bus_dmamap_load_uio() or bus_dmamap_load_mbuf().
Callback2s are of the format:
void client_callback2(void *callback_arg, bus_dma_segment_t
*segs, int nseg, bus_size_t mapsize, int error)
Callback2's behavior is the same as bus_dmamap_callback_t with the addition that the length of the data mapped is provided via mapsize. extra data, extra slay π
bus_dmasync_op_t π
Memory synchronization operation specifier. Bus DMA requires explicit synchronization of memory with its device visible mapping in order to guarantee memory coherency. The bus_dmasync_op_t allows the type of DMA operation that will be or has been performed to be communicated to the system so that the correct coherency measures are taken. The operations are represented as bitfield flags that can be combined together, though it only makes sense to combine PRE flags or POST flags, not both. See the bus_dmamap_sync() description below for more details on how to use these operations.
All operations specified below are performed from the host memory point of view, where a read implies data coming from the device to the host memory, and a write implies data going from the host memory to the device. Alternatively, the operations can be thought of in terms of driver operations, where reading a network packet or storage sector corresponds to a read operation in bus_dma. perspective check, bestie π
BUS_DMASYNC_PREREADβ Perform any synchronization required prior to an update of host memory by the device.BUS_DMASYNC_PREWRITEβ Perform any synchronization required after an update of host memory by the CPU and prior to device access to host memory.BUS_DMASYNC_POSTREADβ Perform any synchronization required after an update of host memory by the device and prior to CPU access to host memory.BUS_DMASYNC_POSTWRITEβ Perform any synchronization required after device access to host memory.
bus_dma_lock_t π
Client specified lock/mutex manipulation method. This will be called from within busdma whenever a client lock needs to be manipulated. In its current form, the function will be called immediately before the callback for a DMA load operation that has been deferred with BUS_DMA_LOCK and immediately after with BUS_DMA_UNLOCK. If the load operation does not need to be deferred, then it will not be called since the function loading the map should be holding the appropriate locks. This method is of the format:
void lockfunc(void *lockfunc_arg, bus_dma_lock_op_t op)
The lockfuncarg argument is specified by the client during tag creation to be passed to all invocations of the callback. The op argument specifies the lock operation to perform.
Two lockfunc implementations are provided for convenience. busdma_lock_mutex() performs standard mutex operations on the sleep mutex provided via lockfuncarg. dflt_lock() will generate a system panic if it is called. It is substituted into the tag when lockfunc is passed as NULL to bus_dma_tag_create() and is useful for tags that should not be used with deferred load operations. panic is not a vibe, but it is the documented behavior π
bus_dma_lock_op_t π
Operations to be performed by the client-specified lockfunc().
BUS_DMA_LOCKβ Acquires and/or locks the client locking primitive.BUS_DMA_UNLOCKβ Releases and/or unlocks the client locking primitive.
π₯ FUNCTIONS π₯
bus_dma_tag_create() π οΈ
bus_dma_tag_create(parent, alignment, boundary, lowaddr, highaddr,
*filtfunc, *filtfuncarg, maxsize, nsegments, maxsegsz, flags,
lockfunc, lockfuncarg, *dmat)
Allocates a DMA tag, and initializes it according to the arguments provided:
parentβ A parent tag from which to inherit restrictions. The restrictions passed in other arguments can only further tighten the restrictions inherited from the parent tag.
All tags created by a device driver must inherit from the tag returned by bus_get_dma_tag() to honor restrictions between the parent bridge, CPU memory, and the device. no skipping the parent, that's the whole family tree π
alignmentβ Alignment constraint, in bytes, of any mappings created using this tag. The alignment must be a power of 2. Hardware that can DMA starting at any address would specify1for byte alignment. Hardware requiring DMA transfers to start on a multiple of 4K would specify4096. βboundaryβ Boundary constraint, in bytes, of the target DMA memory region. The boundary indicates the set of addresses, all multiples of theboundaryargument, that cannot be crossed by a singlebus_dma_segment_t. The boundary must be a power of 2 and must be no smaller than the maximum segment size.0indicates that there are no boundary restrictions. power of 2 or it's not invited to the function π§
Okay so, back to the bus_dma_tag_create() args β the ones we didnβt get to yet:
lowaddr,highaddrβ these are the bounds of the window of bus address space that your device literally cannot touch directly. The window contains every address greater thanlowaddrand less than or equal tohighaddr. Example time: a device that canβt do DMA above 4GB would specify ahighaddrofBUS_SPACE_MAXADDRand alowaddrofBUS_SPACE_MAXADDR_32BIT. Similarly, a device that can only DMA to addresses below 16MB would specify ahighaddrofBUS_SPACE_MAXADDRand alowaddrofBUS_SPACE_MAXADDR_24BIT. Some implementations need some region of device-visible address space β overlapping available host memory β to be outside the window. That area of βsafe memoryβ is used to bounce requests that would otherwise conflict with the exclusion window. π«Άfiltfuncβ formerly the optional filter function; now it must beNULL. No cap.filtfuncargβ must beNULLtoo. πmaxsizeβ maximum size, in bytes, of the sum of all segment lengths in a given DMA mapping associated with this tag.nsegmentsβ number of discontinuities (scatter/gather segments) allowed in a DMA mapped region.maxsegszβ maximum size, in bytes, of a segment in any DMA mapped region associated withdmat.flagsβ are as follows:BUS_DMA_ALLOCNOWβ pre-allocate enough resources to handle at least one map load operation on this tag. If sufficient resources arenβt available,ENOMEMis returned. This should not be used for tags that only describe buffers that will be allocated withbus_dmamem_alloc(). Also, because resources are shared with other tags, this flag does not guarantee that resources will be allocated or reserved exclusively for this tag. Treat it as only a minor optimization.BUS_DMA_COHERENTβ indicates that the DMA engine and CPU are cache-coherent. Cached memory may be used to back allocations created bybus_dmamem_alloc(). Forbus_dma_tag_create(), theBUS_DMA_COHERENTflag is currently implemented on arm64.
lockfuncβ optional lock manipulation function (may beNULL) to be called when busdma needs to manipulate a lock on behalf of the client. IfNULLis specified,dflt_lock()is used.lockfuncargβ optional argument to be passed to the function specified bylockfunc.dmatβ pointer to abus_dma_tag_twhere the resulting DMA tag will be stored.
Returns ENOMEM if sufficient memory is not available for tag creation or allocating mapping resources. Returns EINVAL if either filtfunc or filtarg arguments are not NULL.
π bus_dma_tag_destroy(dmat)
Deallocates the DMA tag dmat that was created by bus_dma_tag_create().
Returns EBUSY if any DMA maps remain associated with dmat, or 0 on success.
πΈ bus_dma_template_init(*template, parent)
Initializes a bus_dma_template_t structure. If the parent argument is non-NULL, this parent tag is associated with the template and will be compiled into the DMA tag that is later created. The values of the parent are not copied into the template. During tag creation in bus_dma_tag_template(), any parameters from the parent tag that are more restrictive than whatβs in the provided template will overwrite what goes into the new tag.
π¦ bus_dma_template_tag(*template, *dmat)
Unpacks a template into a tag and returns the tag via dmat. All return values are identical to bus_dma_tag_create(). The template is not modified by this function, and can be reused and/or freed upon return. Obsessed.
π bus_dma_template_clone(*template, dmat)
Copies the fields from an existing tag to a template. The template does not need to be initialized first β all of its fields will be overwritten by the values contained in the tag. When paired with bus_dma_template_tag(), this function is useful for creating copies of tags.
β¨ bus_dma_template_fill(*template, params[], count)
Fills in the selected fields of the template with the keyed values from the params array. This is not meant to be called directly β use BUS_DMA_TEMPLATE_FILL() instead.
π BUS_DMA_TEMPLATE_FILL(*template, param ...)
Fills in the selected fields of the template with a variable number of key-value parameters. The macros listed below take an argument of the specified type and encapsulate it into a key-value structure that is directly usable as a parameter argument. Multiple parameters may be provided at once.
BD_PARENT()βvoid *BD_ALIGNMENT()βuintmax_tBD_BOUNDARY()βuintmax_tBD_LOWADDR()βvm_paddr_tBD_HIGHADDR()βvm_paddr_tBD_MAXSIZE()βuintmax_tBD_NSEGMENTS()βuintmax_tBD_MAXSEGSIZE()βuintmax_tBD_FLAGS()βuintmax_tBD_LOCKFUNC()βvoid *BD_LOCKFUNCARG()βvoid *
π₯ bus_dmamap_create(dmat, flags, *mapp)
Allocates and initializes a DMA map. Arguments are as follows:
dmatβ DMA tag.flagsβ are as follows:BUS_DMA_COHERENTβ attempt to map the memory loaded with this map such that cache sync operations are as cheap as possible. This flag is typically set on maps when the memory loaded with these will be accessed by both a CPU and a DMA engine β frequently control data, as opposed to streamable data like receive and transmit buffers. Use of this flag does not remove the requirement of usingbus_dmamap_sync(), but it may reduce the cost of performing these operations.
mappβ pointer to abus_dmamap_twhere the resulting DMA map will be stored.
Returns ENOMEM if sufficient memory is not available for creating the map or allocating mapping resources.
π bus_dmamap_destroy(dmat, map)
Frees all resources associated with a given DMA map. Arguments are as follows:
dmatβ DMA tag used to allocatemap.mapβ the DMA map to destroy.
Returns EBUSY if a mapping is still active for map.
π bus_dmamap_load(dmat, map, buf, buflen, *callback, callback_arg, flags)
Creates a mapping in device-visible address space of buflen bytes of buf, associated with the DMA map map. This call will always return immediately and will not block for any reason. Arguments are as follows:
dmatβ DMA tag used to allocatemap.mapβ a DMA map without a currently active mapping.bufβ a kernel virtual address pointer to a contiguous (in KVA) buffer, to be mapped into device-visible address space.buflenβ the size of the buffer.callback,callback_argβ the callback function and its argument. This function is called once sufficient mapping resources are available for the DMA operation. If resources are temporarily unavailable, this function will be deferred until later, but the load operation will still return immediately to the caller. So bestie, callers should not assume that the callback will be called before the load returns, and code should be structured appropriately to handle this. See below for specific flags and error codes that control this behavior.flagsβ are as follows:BUS_DMA_NOWAITβ the load should not be deferred in case of insufficient mapping resources, and instead should return immediately with an appropriate error.BUS_DMA_NOCACHEβ the generated transactions to and from the virtual page are non-cacheable.
Return values to the caller are as follows:
0β the callback has been called and completed. The status of the mapping has been delivered to the callback.EINPROGRESSβ the mapping has been deferred for lack of resources. The callback will be called as soon as resources are available. Callbacks are serviced in FIFO order. β
okay so real talk, bestie: subsequent load operations for the same tag that do not require extra resources will still succeed π . This may result in out-of-order processing of requests. If the caller requires the order of requests to be preserved, then the caller is required to stall subsequent requests until a pending request's callback is invoked. no cap.
ENOMEMβ the load request has failed due to insufficient resources, and the caller specifically used theBUS_DMA_NOWAITflag. πEINVALβ the load request was invalid. The callback has been called and has been provided the same error. This error value may indicate thatdmat,map,buf, orcallbackwere invalid, orbuflenwas larger than themaxsizeargument used to create the DMA tagdmat. π
When the callback is called, it is presented with an error value indicating the disposition of the mapping. Error may be one of the following:
0β the mapping was successful and thedm_segscallback argument contains an array ofbus_dma_segment_telements describing the mapping. This array is only valid during the scope of the callback function. β¨EFBIGβ a mapping could not be achieved within the segment constraints provided in the tag even though the requested allocation size was less thanmaxsize. π
bus_dmamap_load_bio(dmat, map, bio, callback, callback_arg, flags) β¨
This is a variation of bus_dmamap_load() which maps buffers pointed to by bio for DMA transfers. bio may point to either a mapped or unmapped buffer. π«Ά
bus_dmamap_load_ccb(dmat, map, ccb, callback, callback_arg, flags) π¦
This is a variation of bus_dmamap_load() which maps data pointed to by ccb for DMA transfers. The data for ccb may be any of the following types:
CAM_DATA_VADDRβ the data is a single KVA buffer.CAM_DATA_PADDRβ the data is a single bus address range.CAM_DATA_SGβ the data is a scatter/gather list of KVA buffers.CAM_DATA_SG_PADDRβ the data is a scatter/gather list of bus address ranges.CAM_DATA_BIOβ the data is contained in astruct bioattached to the CCB.
bus_dmamap_load_ccb() supports the following CCB XPT function codes:
XPT_ATA_IO
XPT_CONT_TARGET_IO
XPT_SCSI_IO
bus_dmamap_load_crp(dmat, map, crp, callback, callback_arg, flags) β‘
This is a variation of bus_dmamap_load() which maps the input buffer pointed to by crp for DMA transfers. The BUS_DMA_NOWAIT flag is implied, thus no callback deferral will happen. π₯
bus_dmamap_load_crp_buffer(dmat, map, cb, callback, callback_arg, flags) π§
This is a variation of bus_dmamap_load() which maps the crypto data buffer pointed to by cb for DMA transfers. The BUS_DMA_NOWAIT flag is implied, thus no callback deferral will happen. π
bus_dmamap_load_mbuf(dmat, map, mbuf, callback2, callback_arg, flags) π
This is a variation of bus_dmamap_load() which maps mbuf chains for DMA transfers. A bus_size_t argument is also passed to the callback routine, which contains the mbuf chain's packet header length. The BUS_DMA_NOWAIT flag is implied, thus no callback deferral will happen. πΈ
Mbuf chains are assumed to be in kernel virtual address space.
Beside the error values listed for bus_dmamap_load(), EINVAL will be returned if the size of the mbuf chain exceeds the maximum limit of the DMA tag. π
bus_dmamap_load_mbuf_sg(dmat, map, mbuf, segs, nsegs, flags) π
This is just like bus_dmamap_load_mbuf() except that it returns immediately without calling a callback function. It is provided for efficiency. The scatter/gather segment array segs is provided by the caller and filled in directly by the function. The nsegs argument is returned with the number of segments filled in. Returns the same errors as bus_dmamap_load_mbuf(). β¨
bus_dmamap_load_uio(dmat, map, uio, callback2, callback_arg, flags) π
This is a variation of bus_dmamap_load() which maps buffers pointed to by uio for DMA transfers. A bus_size_t argument is also passed to the callback routine, which contains the size of uio, i.e. uio->uio_resid. The BUS_DMA_NOWAIT flag is implied, thus no callback deferral will happen. Returns the same errors as bus_dmamap_load(). πΈ
If uio->uio_segflg is UIO_USERSPACE, then it is assumed that the buffer, uio is in uio->uio_td->td_proc's address space. User space memory must be in-core and wired prior to attempting a map load operation. Pages may be locked using vslock(9). π
bus_dmamap_unload(dmat, map) π«Ά
Unloads a DMA map. Arguments are as follows:
dmatβ DMA tag used to allocate map.mapβ the DMA map that is to be unloaded.
β οΈbus_dmamap_unload()will not perform any implicit synchronization of DMA buffers. This must be done explicitly by a call tobus_dmamap_sync()prior to unloading the map.
bus_dmamap_sync(dmat, map, op) π¦
Performs synchronization of a device visible mapping with the CPU visible memory referenced by that mapping. Arguments are as follows:
dmatβ DMA tag used to allocate map.mapβ the DMA mapping to be synchronized.opβ type of synchronization operation to perform. See the definition ofbus_dmasync_op_tfor a description of the acceptable values forop.
The bus_dmamap_sync() function is the method used to ensure that CPU's and device's direct memory access (DMA) to shared memory is coherent. For example, the CPU might be used to set up the contents of a buffer that is to be made available to a device. To ensure that the data are visible via the device's mapping of that memory, the buffer must be loaded and a DMA sync operation of BUS_DMASYNC_PREWRITE must be performed after the CPU has updated the buffer and before the device access is initiated. If the CPU modifies this buffer again later, another BUS_DMASYNC_PREWRITE sync operation must be performed before an additional device access. Conversely, suppose a device updates memory that is to be read by a CPU. In this case, the buffer must be loaded, and a DMA sync operation of BUS_DMASYNC_PREREAD must be performed before the device access is initiated. The CPU will only be able to see the results of this memory update once the DMA operation has completed and a BUS_DMASYNC_POSTREAD sync operation has been performed. π¦
π If read and write operations are not preceded and followed by the appropriate synchronization operations, behavior is undefined.
bus_dmamem_alloc(dmat, **vaddr, flags, *mapp) π
Allocates memory that is mapped into KVA at the address returned in vaddr and that is permanently loaded into the newly created bus_dmamap_t returned via mapp. Arguments are as follows:
dmatβ DMA tag describing the constraints of the DMA mapping.vaddrβ pointer to a pointer that will hold the returned KVA mapping of the allocated region.flagsβ flags are defined as follows:BUS_DMA_WAITOKβ the routine can safely wait (sleep) for resources.BUS_DMA_NOWAITβ the routine is not allowed to wait for resources. If resources are not available,ENOMEMis returned.BUS_DMA_COHERENTβ attempt to map this memory in a coherent fashion. Seebus_dmamap_create()above for a description of this flag. Forbus_dmamem_alloc(), theBUS_DMA_COHERENTflag is currently implemented on arm and arm64.BUS_DMA_ZEROβ causes the allocated memory to be set to all zeros.BUS_DMA_NOCACHEβ the allocated memory will not be cached in the processor caches. All memory accesses appear on the bus and are executed without reordering. Forbus_dmamem_alloc(), theBUS_DMA_NOCACHEflag is currently implemented on amd64 and i386 where it results in the Strong Uncacheable PAT to be set for the allocated virtual address range.
mappβ pointer to abus_dmamap_twhere the resulting DMA map will be stored.
The size of memory to be allocated is maxsize as specified in the call to bus_dma_tag_create() for dmat. β¨
The current implementation of bus_dmamem_alloc() will allocate all requests as a single segment.
An initial load operation is required to obtain the bus address of the allocated memory, and an unload operation is required before freeing the memory, as described below in bus_dmamem_free(). Maps are automatically handled by this function and should not be explicitly allocated or destroyed.
Although an explicit load is not required for each access to the memory referenced by the returned map, the synchronization requirements as described in the bus_dmamap_sync() section still apply and should be used to achieve portability on architectures without coherent buses. π«Ά
Returns ENOMEM if sufficient memory is not available for completing the operation. π
bus_dmamem_free(dmat, *vaddr, map)β frees memory that was previously allocated bybus_dmamem_alloc(). Any mappings get invalidated, so likeβ¦ they're gone gone. The arguments are:dmatβ the DMA tag.vaddrβ the kernel virtual address of the memory.mapβ the DMA map that's getting invalidated.
πΈ RETURN VALUES πΈ
Okay so real talk: if you pass invalid arguments to any of the functions above, the behavior is undefined β like, we're not even going to pretend to know what happens, bestie. Don't do it. π
If sufficient resources can't be allocated for a given transaction, ENOMEM gets returned. That's the "no memory for you" moment.
Every routine that isn't of type void will return 0 on success or an error code on failure, as discussed above. And all the void routines? They succeed if you give them valid arguments. That's it, that's the whole vibe check. β¨
π LOCKING π
So bus_dma runs on two locking protocols, and honestly you need to know both or you're gonna have a bad time. π
The first is a private global lock that synchronizes access to the bounce buffer pool on the architectures that actually make use of them. This lock is strictly a leaf lock β it's only used internally to bus_dma and is not exposed to clients of the API. So don't go looking for it, it's not for you. π
The second protocol is all about protecting the various resources stored in the tag. Since, like, almost all bus_dma operations happen through requests from the driver that created the tag, the most efficient way to protect the tag resources is through the lock that the driver uses. Iconic teamwork. π
But when bus_dma acts on its own β without being called by the driver β the lock primitive specified in the tag gets acquired and released automatically. The classic example of this? When the bus_dmamap_load() callback function is called from a deferred context instead of the driver context. Main character energy from the framework itself. π
Which brings us to the rule: certain bus_dma functions must always be called with the same lock held that is specified in the tag. Those functions are:
bus_dmamap_load()bus_dmamap_load_bio()bus_dmamap_load_ccb()bus_dmamap_load_mbuf()bus_dmamap_load_mbuf_sg()bus_dmamap_load_uio()bus_dmamap_unload()bus_dmamap_sync()
There is one exception to this rule (yes, there's always one π). It's common practice to call some of these functions during driver start-up without any locks held. So long as there's a guarantee of no possible concurrent use of the tag by different threads during this operation, it is safe to not hold a lock for these functions. Key phrase: no possible concurrent use. Don't get cute with it.
Certain bus_dma operations should not be called with the driver lock held, either because they're already protected by an internal lock, or because they might sleep due to memory or resource allocation. The following functions must not be called with any non-sleepable locks held:
bus_dma_tag_create()bus_dmamap_create()bus_dmamem_alloc()
All other functions don't have a locking protocol at all, so you can call them with or without any system or driver locks held. Free real estate. π«Ά
π SEE ALSO π
And this absolute classic, go read it:
Jason R. Thorpe, βA Machine-Independent DMA Framework for NetBSDβ, Proceedings of the Summer 1998 USENIX Technical Conference, USENIX Association, June 1998. π
π¦ HISTORY π¦
The bus_dma interface first appeared in NetBSD 1.3. A whole era. β
The bus_dma API was adopted from NetBSD for use in the CAM SCSI subsystem. The alterations to the original API were aimed to remove the need for a bus_dma_segment_t array stored in each bus_dmamap_t β while still allowing callers to queue up on scarce resources. Lowkey a glow-up. β¨
π AUTHORS π
The bus_dma interface was designed and implemented by Jason R. Thorpe of the Numerical Aerospace Simulation Facility, NASA Ames Research Center. π
Additional input on the bus_dma design was provided by Chris Demetriou, Charles Hannum, Ross Harvey, Matthew Jacob, Jonathan Stone, and Matt Thomas. The group chat really showed up for this one. π
The bus_dma interface in FreeBSD benefits from the contributions of Justin T. Gibbs, Peter Wemm, Doug Rabson, Matthew N. Dodd, Sam Leffler, Maxime Henrion, Jake Burkholder, Takahashi Yoshihiro, Scott Long and many others. So many legends, no cap. π
This manual page was written by Hiten M. Pandya and Justin T. Gibbs.
That's the whole page bestie, you made it to the end! π Go forth and DMA responsibly. π
And btw, this page is from Debian, dated May 25, 2020, filed under the source/version line BUS_DMA(9) β okay love you, bye! π
πΈπ«Ά
π¦ where this page comes from
- freebsd 15.1: base 15.1
- Copyright (c) 2002, 2003 Hiten M. Pandya
- Copyright (c) 1996, 1997, 1998, 2001 The NetBSD Foundation, Inc
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms