요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
============================================
Dynamic DMA mapping using the generic device
============================================
:Author: James E.J. Bottomley <James.Bottomley@HansenPartnership.com>
This document describes the DMA API. For a more gentle introduction
of the API (and actual examples), see Documentation/core-api/dma-api-howto.rst.
This API is split into two pieces. Part I describes the basic API.
Part II describes extensions for supporting non-coherent memory
machines. Unless you know that your driver absolutely has to support
non-coherent platforms (this is usually only legacy platforms) you
should only use the API described in part I.
Part I - DMA API
----------------
To get the DMA API, you must #include <linux/dma-mapping.h>. This
provides dma_addr_t and the interfaces described below.
A dma_addr_t can hold any valid DMA address for the platform. It can be
given to a device to use as a DMA source or target. A CPU cannot reference
a dma_addr_t directly because there may be translation between its physical
address space and the DMA address space.
Part Ia - Using large DMA-coherent buffers
------------------------------------------
::
void *
dma_alloc_coherent(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t flag)
Coherent memory is memory for which a write by either the device or
the processor can immediately be read by the processor or device
without having to worry about caching effects. (You may however need
to make sure to flush the processor's write buffers before telling
devices to read that memory.)
This routine allocates a region of <size> bytes of coherent memory.
It returns a pointer to the allocated region (in the processor's virtual
address space) or NULL if the allocation failed.
It also returns a <dma_handle> which may be cast to an unsigned integer the
same width as the bus and given to the device as the DMA address base of
the region.
Note: coherent memory can be expensive on some platforms, and the
minimum allocation length may be as big as a page, so you should
consolidate your requests for coherent memory as much as possible.
The simplest way to do that is to use the dma_pool calls (see below).
The flag parameter allows the caller to specify the ``GFP_`` flags (see
kmalloc()) for the allocation (the implementation may ignore flags that affect
the location of the returned memory, like GFP_DMA).
::
void
dma_free_coherent(struct device *dev, size_t size, void *cpu_addr,
dma_addr_t dma_handle)
Free a previously allocated region of coherent memory. dev, size and dma_handle
must all be the same as those passed into dma_alloc_coherent(). cpu_addr must
be the virtual address returned by dma_alloc_coherent().
Note that unlike the sibling allocation call, this routine may only be called
with IRQs enabled.
Part Ib - Using small DMA-coherent buffers
------------------------------------------
To get this part of the DMA API, you must #include <linux/dmapool.h>
Many drivers need lots of small DMA-coherent memory regions for DMA
descriptors or I/O buffers. Rather than allocating in units of a page
or more using dma_alloc_coherent(), you can use DMA pools. These work
much like a struct kmem_cache, except that they use the DMA-coherent allocator,
not __get_free_pages(). Also, they understand common hardware constraints
for alignment, like queue heads needing to be aligned on N-byte boundaries.
.. kernel-doc:: mm/dmapool.c
:export:
.. kernel-doc:: include/linux/dmapool.h
Part Ic - DMA addressing limitations
------------------------------------
DMA mask is a bit mask of the addressable region for the device. In other words,
if applying the DMA mask (a bitwise AND operation) to the DMA address of a
memory region does not clear any bits in the address, then the device can
perform DMA to that memory region.
All the below functions which set a DMA mask may fail if the requested mask
cannot be used with the device, or if the device is not capable of doing DMA.
::
int
dma_set_mask_and_coherent(struct device *dev, u64 mask)
Updates both streaming and coherent DMA masks.
Returns: 0 if successful and a negative error if not.
::
int
dma_set_mask(struct device *dev, u64 mask)
Updates only the streaming DMA mask.
Returns: 0 if successful and a negative error if not.
::
int
dma_set_coherent_mask(struct device *dev, u64 mask)
Updates only the coherent DMA mask.
Returns: 0 if successful and a negative error if not.
::
u64
dma_get_required_mask(struct device *dev)
This API returns the mask that the platform requires to
operate efficiently. Usually this means the returned mask
is the minimum required to cover all of memory. Examining the
required mask gives drivers with variable descriptor sizes the
opportunity to use smaller descriptors as necessary.
Requesting the required mask does not alter the current mask. If you
wish to take advantage of it, you should issue a dma_set_mask()
call to set the mask to the value returned.
::
size_t
dma_max_mapping_size(struct device *dev);
Returns the maximum size of a mapping for the device. The size parameter
of the mapping functions like dma_map_single(), dma_map_page() and
others should not be larger than the returned value.
::
size_t
dma_opt_mapping_size(struct device *dev);
Returns the maximum optimal size of a mapping for the device.
Mapping larger buffers may take much longer in certain scenarios. In
addition, for high-rate short-lived streaming mappings, the upfront time
spent on the mapping may account for an appreciable part of the total
request lifetime. As such, if splitting larger requests incurs no
significant performance penalty, then device drivers are advised to
limit total DMA streaming mappings length to the returned value.
::
bool
dma_need_sync(struct device *dev, dma_addr_t dma_addr);
Returns %true if dma_sync_single_for_{device,cpu} calls are required to
transfer memory ownership. Returns %false if those calls can be skipped.
::
unsigned long
dma_get_merge_boundary(struct device *dev);
Returns the DMA merge boundary. If the device cannot merge any DMA address
segments, the function returns 0.
Part Id - Streaming DMA mappings
--------------------------------
Streaming DMA allows to map an existing buffer for DMA transfers and then
unmap it when finished. Map functions are not guaranteed to succeed, so the
return value must be checked.
.. note::
In particular, mapping may fail for memory not addressable by the
device, e.g. if it is not within the DMA mask of the device and/or a
connecting bus bridge. Streaming DMA functions try to overcome such
addressing constraints, either by using an IOMMU (a device which maps
I/O DMA addresses to physical memory addresses), or by copying the
data to/from a bounce buffer if the kernel is configured with a
:doc:`SWIOTLB <swiotlb>`. However, these methods are not always
available, and even if they are, they may still fail for a number of
reasons.
In short, a device driver may need to be wary of where buffers are
located in physical memory, especially if the DMA mask is less than 32
bits.
::
dma_addr_t
dma_map_single(struct device *dev, void *cpu_addr, size_t size,
enum dma_data_direction direction)
Maps a piece of processor virtual memory so it can be accessed by the
device and returns the DMA address of the memory.
The DMA API uses a strongly typed enumerator for its direction:
======================= =============================================
DMA_NONE no direction (used for debugging)
DMA_TO_DEVICE data is going from the memory to the device
DMA_FROM_DEVICE data is coming from the device to the memory
DMA_BIDIRECTIONAL direction isn't known
======================= =============================================
.. note::
Contiguous kernel virtual space may not be contiguous as
physical memory. Since this API does not provide any scatter/gather
capability, it will fail if the user tries to map a non-physically
contiguous piece of memory. For this reason, memory to be mapped by
this API should be obtained from sources which guarantee it to be
physically contiguous (like kmalloc).
.. warning::
Memory coherency operates at a granularity called the cache
line width. In order for memory mapped by this API to operate
correctly, the mapped region must begin exactly on a cache line
boundary and end exactly on one (to prevent two separately mapped
regions from sharing a single cache line). Since the cache line size
may not be known at compile time, the API will not enforce this
requirement. Therefore, it is recommended that driver writers who
don't take special care to determine the cache line size at run time
only map virtual regions that begin and end on page boundaries (which
are guaranteed also to be cache line boundaries).
DMA_TO_DEVICE synchronisation must be done after the last modification
of the memory region by the software and before it is handed off to
the device. Once this primitive is used, memory covered by this
primitive should be treated as read-only by the device. If the device
may write to it at any point, it should be DMA_BIDIRECTIONAL (see
below).
DMA_FROM_DEVICE synchronisation must be done before the driver
accesses data that may be changed by the device. This memory should
be treated as read-only by the driver. If the driver needs to write
to it at any point, it should be DMA_BIDIRECTIONAL (see below).
DMA_BIDIRECTIONAL requires special handling: it means that the driver
isn't sure if the memory was modified before being handed off to the
device and also isn't sure if the device will also modify it. Thus,
you must always sync bidirectional memory twice: once before the
memory is handed off to the device (to make sure all memory changes
are flushed from the processor) and once before the data may be
accessed after being used by the device (to make sure any processor
cache lines are updated with data that the device may have changed).
::
void
dma_unmap_single(struct device *dev, dma_addr_t dma_addr, size_t size,
enum dma_data_direction direction)
Unmaps the region previously mapped. All the parameters passed in
must be identical to those passed to (and returned by) dma_map_single().
::
dma_addr_t
dma_map_page(struct device *dev, struct page *page,
unsigned long offset, size_t size,
enum dma_data_direction direction)
void
dma_unmap_page(struct device *dev, dma_addr_t dma_address, size_t size,
enum dma_data_direction direction)
API for mapping and unmapping for pages. All the notes and warnings
for the other mapping APIs apply here. Also, although the <offset>
and <size> parameters are provided to do partial page mapping, it is
recommended that you never use these unless you really know what the
cache width is.
::
dma_addr_t
dma_map_resource(struct device *dev, phys_addr_t phys_addr, size_t size,
enum dma_data_direction dir, unsigned long attrs)
void
dma_unmap_resource(struct device *dev, dma_addr_t addr, size_t size,
enum dma_data_direction dir, unsigned long attrs)
API for mapping and unmapping for MMIO resources. All the notes and
warnings for the other mapping APIs apply here. The API should only be
used to map device MMIO resources, mapping of RAM is not permitted.
::
int
dma_mapping_error(struct device *dev, dma_addr_t dma_addr)
In some circumstances dma_map_single(), dma_map_page() and dma_map_resource()
will fail to create a mapping. A driver can check for these errors by testing
the returned DMA address with dma_mapping_error(). A non-zero return value
means the mapping could not be created and the driver should take appropriate
action (e.g. reduce current DMA mapping usage or delay and try again later).
::
int
dma_map_sg(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction direction)
Maps a scatter/gather list for DMA. Returns the number of DMA address segments
mapped, which may be smaller than <nents> passed in if several consecutive
sglist entries are merged (e.g. with an IOMMU, or if some adjacent segments
just happen to be physically contiguous).
Please note that the sg cannot be mapped again if it has been mapped once.
The mapping process is allowed to destroy information in the sg.
As with the other mapping interfaces, dma_map_sg() can fail. When it
does, 0 is returned and a driver must take appropriate action. It is
critical that the driver do something, in the case of a block driver
aborting the request or even oopsing is better than doing nothing and
corrupting the filesystem.
With scatterlists, you use the resulting mapping like this::
int i, count = dma_map_sg(dev, sglist, nents, direction);
struct scatterlist *sg;
for_each_sg(sglist, sg, count, i) {
hw_address[i] = sg_dma_address(sg);
hw_len[i] = sg_dma_len(sg);
}
where nents is the number of entries in the sglist.
The implementation is free to merge several consecutive sglist entries
into one. The returned number is the actual number of sg entries it
mapped them to. On failure, 0 is returned.
Then you should loop count times (note: this can be less than nents times)
and use sg_dma_address() and sg_dma_len() macros where you previously
accessed sg->address and sg->length as shown above.
::
void
dma_unmap_sg(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction direction)
Unmap the previously mapped scatter/gather list. All the parameters
must be the same as those and passed in to the scatter/gather mapping
API.
Note: <nents> must be the number you passed in, *not* the number of
DMA address entries returned.
::
void
dma_sync_single_for_cpu(struct device *dev, dma_addr_t dma_handle,
size_t size,
enum dma_data_direction direction)
void
dma_sync_single_for_device(struct device *dev, dma_addr_t dma_handle,
size_t size,
enum dma_data_direction direction)
void
dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
int nents,
enum dma_data_direction direction)
void
dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
int nents,
enum dma_data_direction direction)
Synchronise a single contiguous or scatter/gather mapping for the CPU
and device. With the sync_sg API, all the parameters must be the same
as those passed into the sg mapping API. With the sync_single API,
you can use dma_handle and size parameters that aren't identical to
those passed into the single mapping API to do a partial sync.
.. note::
You must do this:
- Before reading values that have been written by DMA from the device
(use the DMA_FROM_DEVICE direction)
- After writing values that will be written to the device using DMA
(use the DMA_TO_DEVICE) direction
- before *and* after handing memory to the device if the memory is
DMA_BIDIRECTIONAL
See also dma_map_single().
::
dma_addr_t
dma_map_single_attrs(struct device *dev, void *cpu_addr, size_t size,
enum dma_data_direction dir,
unsigned long attrs)
void
dma_unmap_single_attrs(struct device *dev, dma_addr_t dma_addr,
size_t size, enum dma_data_direction dir,
unsigned long attrs)
int
dma_map_sg_attrs(struct device *dev, struct scatterlist *sgl,
int nents, enum dma_data_direction dir,
unsigned long attrs)
void
dma_unmap_sg_attrs(struct device *dev, struct scatterlist *sgl,
int nents, enum dma_data_direction dir,
unsigned long attrs)
The four functions above are just like the counterpart functions
without the _attrs suffixes, except that they pass an optional
dma_attrs.
The interpretation of DMA attributes is architecture-specific, and
each attribute should be documented in
Documentation/core-api/dma-attributes.rst.
If dma_attrs are 0, the semantics of each of these functions
is identical to those of the corresponding function
without the _attrs suffix. As a result dma_map_single_attrs()
can generally replace dma_map_single(), etc.
As an example of the use of the ``*_attrs`` functions, here's how
you could pass an attribute DMA_ATTR_FOO when mapping memory
for DMA::
#include <linux/dma-mapping.h>
/* DMA_ATTR_FOO should be defined in linux/dma-mapping.h and
* documented in Documentation/core-api/dma-attributes.rst */
...
unsigned long attr;
attr |= DMA_ATTR_FOO;
....
n = dma_map_sg_attrs(dev, sg, nents, DMA_TO_DEVICE, attr);
....
Architectures that care about DMA_ATTR_FOO would check for its
presence in their implementations of the mapping and unmapping
routines, e.g.:::
void whizco_dma_map_sg_attrs(struct device *dev, dma_addr_t dma_addr,
size_t size, enum dma_data_direction dir,
unsigned long attrs)
{
....
if (attrs & DMA_ATTR_FOO)
/* twizzle the frobnozzle */
....
}
Part Ie - IOVA-based DMA mappings
---------------------------------
These APIs allow a very efficient mapping when using an IOMMU. They are an
optional path that requires extra code and are only recommended for drivers
where DMA mapping performance, or the space usage for storing the DMA addresses
matter. All the considerations from the previous section apply here as well.
::
bool dma_iova_try_alloc(struct device *dev, struct dma_iova_state *state,
phys_addr_t phys, size_t size);
Is used to try to allocate IOVA space for mapping operation. If it returns
false this API can't be used for the given device and the normal streaming
DMA mapping API should be used. The ``struct dma_iova_state`` is allocated
by the driver and must be kept around until unmap time.
::
static inline bool dma_use_iova(struct dma_iova_state *state)
Can be used by the driver to check if the IOVA-based API is used after a
call to dma_iova_try_alloc. This can be useful in the unmap path.
::
int dma_iova_link(struct device *dev, struct dma_iova_state *state,
phys_addr_t phys, size_t offset, size_t size,
enum dma_data_direction dir, unsigned long attrs);
Is used to link ranges to the IOVA previously allocated. The start of all
but the first call to dma_iova_link for a given state must be aligned
to the DMA merge boundary returned by ``dma_get_merge_boundary())``, and
the size of all but the last range must be aligned to the DMA merge boundary
as well.
::
int dma_iova_sync(struct device *dev, struct dma_iova_state *state,
size_t offset, size_t size);
Must be called to sync the IOMMU page tables for IOVA-range mapped by one or
more calls to ``dma_iova_link()``.
For drivers that use a one-shot mapping, all ranges can be unmapped and the
IOVA freed by calling:
::
void dma_iova_destroy(struct device *dev, struct dma_iova_state *state,
size_t mapped_len, enum dma_data_direction dir,
unsigned long attrs);
Alternatively drivers can dynamically manage the IOVA space by unmapping
and mapping individual regions. In that case
::
void dma_iova_unlink(struct device *dev, struct dma_iova_state *state,
size_t offset, size_t size, enum dma_data_direction dir,
unsigned long attrs);
is used to unmap a range previously mapped, and
::
void dma_iova_free(struct device *dev, struct dma_iova_state *state);
is used to free the IOVA space. All regions must have been unmapped using
``dma_iova_unlink()`` before calling ``dma_iova_free()``.
Part II - Non-coherent DMA allocations
--------------------------------------
These APIs allow to allocate pages that are guaranteed to be DMA addressable
by the passed in device, but which need explicit management of memory ownership
for the kernel vs the device.
If you don't understand how cache line coherency works between a processor and
an I/O device, you should not be using this part of the API.
::
struct page *
dma_alloc_pages(struct device *dev, size_t size, dma_addr_t *dma_handle,
enum dma_data_direction dir, gfp_t gfp)
This routine allocates a region of <size> bytes of non-coherent memory. It
returns a pointer to first struct page for the region, or NULL if the
allocation failed. The resulting struct page can be used for everything a
struct page is suitable for.
It also returns a <dma_handle> which may be cast to an unsigned integer the
same width as the bus and given to the device as the DMA address base of
the region.
The dir parameter specified if data is read and/or written by the device,
see dma_map_single() for details.
The gfp parameter allows the caller to specify the ``GFP_`` flags (see
kmalloc()) for the allocation, but rejects flags used to specify a memory
zone such as GFP_DMA or GFP_HIGHMEM.
Before giving the memory to the device, dma_sync_single_for_device() needs
to be called, and before reading memory written by the device,
dma_sync_single_for_cpu(), just like for streaming DMA mappings that are
reused.
::
void
dma_free_pages(struct device *dev, size_t size, struct page *page,
dma_addr_t dma_handle, enum dma_data_direction dir)
Free a region of memory previously allocated using dma_alloc_pages().
dev, size, dma_handle and dir must all be the same as those passed into
dma_alloc_pages(). page must be the pointer returned by dma_alloc_pages().
::
int
dma_mmap_pages(struct device *dev, struct vm_area_struct *vma,
size_t size, struct page *page)
Map an allocation returned from dma_alloc_pages() into a user address space.
dev and size must be the same as those passed into dma_alloc_pages().
page must be the pointer returned by dma_alloc_pages().
::
void *
dma_alloc_noncoherent(struct device *dev, size_t size,
dma_addr_t *dma_handle, enum dma_data_direction dir,
gfp_t gfp)
This routine is a convenient wrapper around dma_alloc_pages that returns the
kernel virtual address for the allocated memory instead of the page structure.
::
void
dma_free_noncoherent(struct device *dev, size_t size, void *cpu_addr,
dma_addr_t dma_handle, enum dma_data_direction dir)
Free a region of memory previously allocated using dma_alloc_noncoherent().
dev, size, dma_handle and dir must all be the same as those passed into
dma_alloc_noncoherent(). cpu_addr must be the virtual address returned by
dma_alloc_noncoherent().
::
struct sg_table *
dma_alloc_noncontiguous(struct device *dev, size_t size,
enum dma_data_direction dir, gfp_t gfp,
unsigned long attrs);
This routine allocates <size> bytes of non-coherent and possibly non-contiguous
memory. It returns a pointer to struct sg_table that describes the allocated
and DMA mapped memory, or NULL if the allocation failed. The resulting memory
can be used for struct page mapped into a scatterlist are suitable for.
The return sg_table is guaranteed to have 1 single DMA mapped segment as
indicated by sgt->nents, but it might have multiple CPU side segments as
indicated by sgt->orig_nents.
The dir parameter specified if data is read and/or written by the device,
see dma_map_single() for details.
The gfp parameter allows the caller to specify the ``GFP_`` flags (see
kmalloc()) for the allocation, but rejects flags used to specify a memory
zone such as GFP_DMA or GFP_HIGHMEM.
The attrs argument must be either 0 or DMA_ATTR_ALLOC_SINGLE_PAGES.
Before giving the memory to the device, dma_sync_sgtable_for_device() needs
to be called, and before reading memory written by the device,
dma_sync_sgtable_for_cpu(), just like for streaming DMA mappings that are
reused.
::
void
dma_free_noncontiguous(struct device *dev, size_t size,
struct sg_table *sgt,
enum dma_data_direction dir)
Free memory previously allocated using dma_alloc_noncontiguous(). dev, size,
and dir must all be the same as those passed into dma_alloc_noncontiguous().
sgt must be the pointer returned by dma_alloc_noncontiguous().
::
void *
dma_vmap_noncontiguous(struct device *dev, size_t size,
struct sg_table *sgt)
Return a contiguous kernel mapping for an allocation returned from
dma_alloc_noncontiguous(). dev and size must be the same as those passed into
dma_alloc_noncontiguous(). sgt must be the pointer returned by
dma_alloc_noncontiguous().
Once a non-contiguous allocation is mapped using this function, the
flush_kernel_vmap_range() and invalidate_kernel_vmap_range() APIs must be used
to manage the coherency between the kernel mapping, the device and user space
mappings (if any).
::
void
dma_vunmap_noncontiguous(struct device *dev, void *vaddr)
Unmap a kernel mapping returned by dma_vmap_noncontiguous(). dev must be the
same the one passed into dma_alloc_noncontiguous(). vaddr must be the pointer
returned by dma_vmap_noncontiguous().
::
int
dma_mmap_noncontiguous(struct device *dev, struct vm_area_struct *vma,
size_t size, struct sg_table *sgt)
Map an allocation returned from dma_alloc_noncontiguous() into a user address
space. dev and size must be the same as those passed into
dma_alloc_noncontiguous(). sgt must be the pointer returned by
dma_alloc_noncontiguous().
::
int
dma_get_cache_alignment(void)
Returns the processor cache alignment. This is the absolute minimum
alignment *and* width that you must observe when either mapping
memory or doing partial flushes.
.. note::
This API may return a number *larger* than the actual cache
line, but it will guarantee that one or more cache lines fit exactly
into the width returned by this call. It will also always be a power
of two for easy alignment.
Part III - Debug drivers use of the DMA API
-------------------------------------------
The DMA API as described above has some constraints. DMA addresses must be
released with the corresponding function with the same size for example. With
the advent of hardware IOMMUs it becomes more and more important that drivers
do not violate those constraints. In the worst case such a violation can
result in data corruption up to destroyed filesystems.
To debug drivers and find bugs in the usage of the DMA API checking code can
be compiled into the kernel which will tell the developer about those
violations. If your architecture supports it you can select the "Enable
debugging of DMA API usage" option in your kernel configuration. Enabling this
option has a performance impact. Do not enable it in production kernels.
If you boot the resulting kernel will contain code which does some bookkeeping
about what DMA memory was allocated for which device. If this code detects an
error it prints a warning message with some details into your kernel log. An
example warning message may look like this::
WARNING: at /data2/repos/linux-2.6-iommu/lib/dma-debug.c:448
check_unmap+0x203/0x490()
Hardware name:
forcedeth 0000:00:08.0: DMA-API: device driver frees DMA memory with wrong
function [device address=0x00000000640444be] [size=66 bytes] [mapped as
single] [unmapped as page]
Modules linked in: nfsd exportfs bridge stp llc r8169
Pid: 0, comm: swapper Tainted: G W 2.6.28-dmatest-09289-g8bb99c0 #1
Call Trace:
<IRQ> [<ffffffff80240b22>] warn_slowpath+0xf2/0x130
[<ffffffff80647b70>] _spin_unlock+0x10/0x30
[<ffffffff80537e75>] usb_hcd_link_urb_to_ep+0x75/0xc0
[<ffffffff80647c22>] _spin_unlock_irqrestore+0x12/0x40
[<ffffffff8055347f>] ohci_urb_enqueue+0x19f/0x7c0
[<ffffffff80252f96>] queue_work+0x56/0x60
[<ffffffff80237e10>] enqueue_task_fair+0x20/0x50
[<ffffffff80539279>] usb_hcd_submit_urb+0x379/0xbc0
[<ffffffff803b78c3>] cpumask_next_and+0x23/0x40
[<ffffffff80235177>] find_busiest_group+0x207/0x8a0
[<ffffffff8064784f>] _spin_lock_irqsave+0x1f/0x50
[<ffffffff803c7ea3>] check_unmap+0x203/0x490
[<ffffffff803c8259>] debug_dma_unmap_phys+0x49/0x50
[<ffffffff80485f26>] nv_tx_done_optimized+0xc6/0x2c0
[<ffffffff80486c13>] nv_nic_irq_optimized+0x73/0x2b0
[<ffffffff8026df84>] handle_IRQ_event+0x34/0x70
[<ffffffff8026ffe9>] handle_edge_irq+0xc9/0x150
[<ffffffff8020e3ab>] do_IRQ+0xcb/0x1c0
[<ffffffff8020c093>] ret_from_intr+0x0/0xa
<EOI> <4>---[ end trace f6435a98e2a38c0e ]---
The driver developer can find the driver and the device including a stacktrace
of the DMA API call which caused this warning.
Per default only the first error will result in a warning message. All other
errors will only silently counted. This limitation exist to prevent the code
from flooding your kernel log. To support debugging a device driver this can
be disabled via debugfs. See the debugfs interface documentation below for
details.
The debugfs directory for the DMA API debugging code is called dma-api/. In
this directory the following files can currently be found:
=============================== ===============================================
dma-api/all_errors This file contains a numeric value. If this
value is not equal to zero the debugging code
will print a warning for every error it finds
into the kernel log. Be careful with this
option, as it can easily flood your logs.
dma-api/disabled This read-only file contains the character 'Y'
if the debugging code is disabled. This can
happen when it runs out of memory or if it was
disabled at boot time
dma-api/dump This read-only file contains current DMA
mappings.
dma-api/error_count This file is read-only and shows the total
numbers of errors found.
dma-api/num_errors The number in this file shows how many
warnings will be printed to the kernel log
before it stops. This number is initialized to
one at system boot and be set by writing into
this file
dma-api/min_free_entries This read-only file can be read to get the
minimum number of free dma_debug_entries the
allocator has ever seen. If this value goes
down to zero the code will attempt to increase
nr_total_entries to compensate.
dma-api/num_free_entries The current number of free dma_debug_entries
in the allocator.
dma-api/nr_total_entries The total number of dma_debug_entries in the
allocator, both free and used.
dma-api/driver_filter You can write a name of a driver into this file
to limit the debug output to requests from that
particular driver. Write an empty string to
that file to disable the filter and see
all errors again.
=============================== ===============================================
If you have this code compiled into your kernel it will be enabled by default.
If you want to boot without the bookkeeping anyway you can provide
'dma_debug=off' as a boot parameter. This will disable DMA API debugging.
Notice that you can not enable it again at runtime. You have to reboot to do
so.
If you want to see debug messages only for a special device driver you can
specify the dma_debug_driver=<drivername> parameter. This will enable the
driver filter at boot time. The debug code will only print errors for that
driver afterwards. This filter can be disabled or changed later using debugfs.
When the code disables itself at runtime this is most likely because it ran
out of dma_debug_entries and was unable to allocate more on-demand. 65536
entries are preallocated at boot - if this is too low for you boot with
'dma_debug_entries=<your_desired_number>' to overwrite the default. Note
that the code allocates entries in batches, so the exact number of
preallocated entries may be greater than the actual number requested. The
code will print to the kernel log each time it has dynamically allocated
as many entries as were initially preallocated. This is to indicate that a
larger preallocation size may be appropriate, or if it happens continually
that a driver may be leaking mappings.
::
void
debug_dma_mapping_error(struct device *dev, dma_addr_t dma_addr);
dma-debug interface debug_dma_mapping_error() to debug drivers that fail
to check DMA mapping errors on addresses returned by dma_map_single() and
dma_map_page() interfaces. This interface clears a flag set by
debug_dma_map_phys() to indicate that dma_mapping_error() has been called by
the driver. When driver does unmap, debug_dma_unmap() checks the flag and if
this flag is still set, prints warning message that includes call trace that
leads up to the unmap. This interface can be called from dma_mapping_error()
routines to enable DMA mapping error check debugging.
Functions and structures
========================
.. kernel-doc:: include/linux/scatterlist.h
.. kernel-doc:: lib/scatterlist.c
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
Generic device를 사용하는 dynamic DMA mapping
1-15Dynamic DMA mapping using the generic device (generic device를 사용하는 동적 DMA mapping)
저자는 James E.J. Bottomley <James.Bottomley@HansenPartnership.com>입니다.
이 문서는 DMA API를 설명합니다. 더 쉬운 소개와 실제 예제는 `Documentation/core-api/dma-api-howto.rst`를 참고하십시오.
API는 두 부분으로 나뉩니다. Part I은 기본 API를, Part II는 non-coherent memory machine 지원 확장을 설명합니다. Driver가 보통 legacy platform인 non-coherent platform을 반드시 지원해야 한다는 확신이 없다면 Part I의 API만 사용해야 합니다.
Part I 기본 DMA API
16-26Part I - DMA API
DMA API를 사용하려면 `#include <linux/dma-mapping.h>`가 필요합니다. 이 header는 `dma_addr_t`와 아래 interface를 제공합니다.
`dma_addr_t`는 platform에서 유효한 모든 DMA address를 담을 수 있고 DMA source 또는 target으로 device에 전달할 수 있습니다. CPU physical address space와 DMA address space 사이에 변환이 있을 수 있으므로 CPU가 `dma_addr_t`를 직접 참조할 수는 없습니다.
Part Ia 큰 DMA-coherent buffer
27-73Part Ia - 큰 DMA-coherent buffer 사용
void *
dma_alloc_coherent(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t flag)
Coherent memory는 device나 processor 어느 쪽이 write해도 caching effect를 걱정하지 않고 상대가 즉시 읽을 수 있는 memory입니다. 다만 device에 읽으라고 알리기 전에 processor write buffer를 flush해야 할 수 있습니다.
`dma_alloc_coherent()`는 `size` byte의 coherent memory region을 allocate합니다. 성공하면 processor virtual address space의 pointer를, 실패하면 `NULL`을 반환합니다. 또한 bus와 같은 폭의 unsigned integer로 cast하여 device에 region의 DMA address base로 줄 수 있는 `dma_handle`을 반환합니다.
일부 platform에서 coherent memory는 비용이 크고 최소 allocation 길이가 한 page일 수 있습니다. 요청을 가능한 한 합치는 것이 좋으며 가장 간단한 방법은 아래의 `dma_pool` 호출을 사용하는 것입니다.
`flag` parameter로 allocation의 `GFP_` flag를 지정합니다. 의미는 `kmalloc()`을 참고하십시오. 구현은 `GFP_DMA`처럼 반환 memory 위치에 영향을 주는 flag를 무시할 수 있습니다.
void
dma_free_coherent(struct device *dev, size_t size, void *cpu_addr,
dma_addr_t dma_handle)
이 함수는 앞서 allocate한 coherent memory region을 free합니다. `dev`, `size`, `dma_handle`은 `dma_alloc_coherent()`에 전달한 값과 같아야 하며 `cpu_addr`는 그 함수가 반환한 virtual address여야 합니다.
Allocation 함수와 달리 `dma_free_coherent()`는 IRQ가 활성화된 상태에서만 호출할 수 있습니다.
Part Ib 작은 DMA-coherent buffer
74-91Part Ib - 작은 DMA-coherent buffer 사용
이 DMA API 부분을 사용하려면 `#include <linux/dmapool.h>`가 필요합니다.
많은 driver는 DMA descriptor나 I/O buffer용 작은 DMA-coherent memory region을 많이 필요로 합니다. `dma_alloc_coherent()`로 page 이상 단위로 allocate하는 대신 DMA pool을 사용할 수 있습니다. DMA pool은 `struct kmem_cache`와 비슷하지만 `__get_free_pages()`가 아니라 DMA-coherent allocator를 사용하고, queue head의 N-byte boundary 정렬 같은 hardware alignment constraint를 이해합니다.
공개 API의 kernel-doc은 `mm/dmapool.c`의 exported symbol과 `include/linux/dmapool.h`에서 가져옵니다.
Part Ic DMA 주소 지정 한계
92-183Part Ic - DMA addressing limitation
DMA mask는 device가 address할 수 있는 영역의 bit mask입니다. Memory region의 DMA address와 mask를 bitwise AND했을 때 address의 bit가 하나도 지워지지 않으면 device가 그 region에 DMA할 수 있습니다.
아래의 DMA mask 설정 함수는 요청한 mask를 device와 함께 사용할 수 없거나 device가 DMA를 수행할 수 없으면 실패할 수 있습니다.
int
dma_set_mask_and_coherent(struct device *dev, u64 mask)
`dma_set_mask_and_coherent()`는 streaming과 coherent DMA mask를 모두 갱신하며 성공하면 0, 실패하면 음수 error를 반환합니다.
int
dma_set_mask(struct device *dev, u64 mask)
`dma_set_mask()`는 streaming DMA mask만 갱신하며 성공하면 0, 실패하면 음수 error를 반환합니다.
int
dma_set_coherent_mask(struct device *dev, u64 mask)
`dma_set_coherent_mask()`는 coherent DMA mask만 갱신하며 성공하면 0, 실패하면 음수 error를 반환합니다.
u64
dma_get_required_mask(struct device *dev)
`dma_get_required_mask()`는 platform이 효율적으로 동작하는 데 필요한 mask를 반환합니다. 보통 전체 memory를 덮는 최소 mask이며, variable descriptor size를 지원하는 driver는 이를 보고 더 작은 descriptor를 선택할 수 있습니다. 이 조회는 현재 mask를 바꾸지 않으므로 활용하려면 반환값으로 `dma_set_mask()`를 호출해야 합니다.
size_t
dma_max_mapping_size(struct device *dev);
`dma_max_mapping_size()`는 device에서 가능한 mapping의 최대 size를 반환합니다. `dma_map_single()`, `dma_map_page()` 같은 mapping 함수의 size parameter가 이 값을 넘으면 안 됩니다.
size_t
dma_opt_mapping_size(struct device *dev);
`dma_opt_mapping_size()`는 최적 mapping의 최대 size를 반환합니다. 일부 상황에서 큰 buffer mapping은 훨씬 오래 걸리며, 짧게 유지되는 고속 streaming mapping에서는 준비 시간이 전체 request lifetime의 상당 부분일 수 있습니다. 큰 request를 나누어도 성능 손해가 크지 않다면 전체 DMA streaming mapping 길이를 반환값 이하로 제한하는 것이 좋습니다.
bool
dma_need_sync(struct device *dev, dma_addr_t dma_addr);
`dma_need_sync()`는 memory ownership 전환에 `dma_sync_single_for_{device,cpu}` 호출이 필요하면 `%true`, 생략할 수 있으면 `%false`를 반환합니다.
unsigned long
dma_get_merge_boundary(struct device *dev);
`dma_get_merge_boundary()`는 DMA merge boundary를 반환합니다. Device가 DMA address segment를 전혀 merge할 수 없으면 0을 반환합니다.
Part Id streaming single mapping과 방향
184-267Part Id - Streaming DMA mapping
Streaming DMA는 기존 buffer를 DMA transfer용으로 mapping하고 끝나면 unmap합니다. Map 함수는 성공이 보장되지 않으므로 반환값을 검사해야 합니다.
Device나 연결 bus bridge의 DMA mask 밖에 있는 memory는 mapping이 실패할 수 있습니다. Streaming DMA 함수는 I/O DMA address를 physical memory address로 mapping하는 IOMMU를 사용하거나, kernel에 `SWIOTLB`가 구성되어 있으면 bounce buffer로 data를 복사해 제약을 극복하려 합니다. 하지만 이 기능들이 항상 제공되는 것은 아니며 다른 이유로도 실패할 수 있습니다. 특히 DMA mask가 32-bit보다 작다면 driver는 buffer의 physical memory 위치를 주의해야 합니다.
dma_addr_t
dma_map_single(struct device *dev, void *cpu_addr, size_t size,
enum dma_data_direction direction)
`dma_map_single()`은 processor virtual memory 일부를 device가 접근할 수 있도록 mapping하고 그 memory의 DMA address를 반환합니다.
DMA API의 direction은 강한 type의 enumerator입니다.
| Direction | 의미 |
|---|---|
| DMA_NONE | 방향 없음, debugging에 사용 |
| DMA_TO_DEVICE | Memory에서 device로 data 이동 |
| DMA_FROM_DEVICE | Device에서 memory로 data 이동 |
| DMA_BIDIRECTIONAL | 방향을 알 수 없음 |
연속된 kernel virtual space가 physical memory에서도 연속이라는 보장은 없습니다. 이 API는 scatter/gather 기능이 없으므로 물리적으로 연속되지 않은 memory를 mapping하면 실패합니다. 따라서 `kmalloc()`처럼 physical continuity를 보장하는 source에서 얻은 memory를 사용해야 합니다.
Memory coherency 단위는 cache line width입니다. Mapping region은 서로 다른 region이 같은 cache line을 공유하지 않도록 cache line boundary에서 정확히 시작하고 끝나야 합니다. Compile time에 cache line size를 모를 수 있어 API가 강제하지 않으므로 runtime size를 별도로 처리하지 않는 driver는 page boundary에서 시작하고 끝나는 virtual region만 mapping하는 것이 좋습니다. Page boundary는 cache line boundary이기도 합니다.
`DMA_TO_DEVICE` synchronization은 software가 memory region을 마지막으로 수정한 뒤 device에 넘기기 전에 수행합니다. 그 뒤 해당 memory는 device 관점에서 read-only로 취급해야 하며 device가 쓸 수 있다면 `DMA_BIDIRECTIONAL`을 사용해야 합니다.
`DMA_FROM_DEVICE` synchronization은 driver가 device가 바꿨을 수 있는 data에 접근하기 전에 수행합니다. 이 memory는 driver 관점에서 read-only로 취급해야 하며 driver가 써야 한다면 `DMA_BIDIRECTIONAL`을 사용합니다.
`DMA_BIDIRECTIONAL`은 memory를 device에 넘기기 전에 driver가 수정했는지, device도 수정할지 모두 확실하지 않은 경우입니다. 따라서 device에 넘기기 전 processor의 변경을 flush하기 위해 한 번, device 사용 뒤 접근하기 전 device가 바꾼 data로 processor cache line을 갱신하기 위해 한 번, 항상 두 번 sync해야 합니다.
Streaming unmap, page, resource와 오류 API
268-318void
dma_unmap_single(struct device *dev, dma_addr_t dma_addr, size_t size,
enum dma_data_direction direction)
`dma_unmap_single()`은 앞서 mapping한 region을 unmap합니다. 모든 parameter는 `dma_map_single()`에 전달하고 반환받은 값과 동일해야 합니다.
dma_addr_t
dma_map_page(struct device *dev, struct page *page,
unsigned long offset, size_t size,
enum dma_data_direction direction)
void
dma_unmap_page(struct device *dev, dma_addr_t dma_address, size_t size,
enum dma_data_direction direction)
`dma_map_page()`와 `dma_unmap_page()`는 page를 mapping하고 unmap하는 API입니다. 다른 mapping API의 모든 note와 warning이 적용됩니다. `offset`과 `size`로 partial page mapping을 할 수 있지만 cache width를 정확히 아는 경우가 아니라면 사용하지 않는 것이 좋습니다.
dma_addr_t
dma_map_resource(struct device *dev, phys_addr_t phys_addr, size_t size,
enum dma_data_direction dir, unsigned long attrs)
void
dma_unmap_resource(struct device *dev, dma_addr_t addr, size_t size,
enum dma_data_direction dir, unsigned long attrs)
`dma_map_resource()`와 `dma_unmap_resource()`는 MMIO resource를 mapping하고 unmap합니다. 다른 mapping API의 note와 warning이 모두 적용되며 device MMIO resource에만 사용해야 하고 RAM mapping은 허용되지 않습니다.
int
dma_mapping_error(struct device *dev, dma_addr_t dma_addr)
`dma_map_single()`, `dma_map_page()`, `dma_map_resource()`는 mapping 생성에 실패할 수 있습니다. Driver는 반환된 DMA address를 `dma_mapping_error()`로 검사합니다. 0이 아닌 반환값은 mapping 실패를 뜻하므로 현재 DMA mapping 사용량을 줄이거나 지연 후 재시도하는 등 적절히 처리해야 합니다.
Streaming scatter/gather mapping
319-371int
dma_map_sg(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction direction)
`dma_map_sg()`는 scatter/gather list를 DMA용으로 mapping하고 DMA address segment 수를 반환합니다. 연속된 sglist entry를 IOMMU로 merge하거나 인접 segment가 우연히 물리적으로 연속이면 반환값이 입력 `nents`보다 작을 수 있습니다.
한 번 mapping한 `sg`는 다시 mapping할 수 없습니다. Mapping 과정은 `sg` 안의 정보를 파괴할 수 있습니다.
`dma_map_sg()`도 실패할 수 있으며 0을 반환합니다. Driver는 반드시 처리해야 합니다. Block driver라면 아무것도 하지 않아 filesystem을 손상시키는 것보다 request를 abort하거나 심지어 oops하는 편이 낫습니다.
Scatterlist mapping 결과는 다음처럼 사용합니다.
int i, count = dma_map_sg(dev, sglist, nents, direction);
struct scatterlist *sg;
for_each_sg(sglist, sg, count, i) {
hw_address[i] = sg_dma_address(sg);
hw_len[i] = sg_dma_len(sg);
}
`nents`는 `sglist` entry 수입니다. 구현은 여러 연속 entry를 하나로 merge할 수 있고 반환값은 실제 mapping된 sg entry 수이며 실패 시 0입니다. 반환된 `count`만큼 순회하면서 기존 `sg->address`, `sg->length` 대신 `sg_dma_address()`와 `sg_dma_len()`을 사용합니다.
void
dma_unmap_sg(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction direction)
`dma_unmap_sg()`는 앞서 mapping한 scatter/gather list를 unmap하며 parameter는 mapping API에 전달한 것과 같아야 합니다. 특히 `nents`는 반환된 DMA address entry 수가 아니라 입력으로 전달한 수여야 합니다.
Streaming mapping 동기화
372-413void
dma_sync_single_for_cpu(struct device *dev, dma_addr_t dma_handle,
size_t size,
enum dma_data_direction direction)
void
dma_sync_single_for_device(struct device *dev, dma_addr_t dma_handle,
size_t size,
enum dma_data_direction direction)
void
dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
int nents,
enum dma_data_direction direction)
void
dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
int nents,
enum dma_data_direction direction)
이 함수들은 single contiguous 또는 scatter/gather mapping을 CPU와 device에 맞게 synchronize합니다. `sync_sg` API의 모든 parameter는 sg mapping API에 전달한 것과 같아야 합니다. `sync_single` API는 single mapping 때와 다른 `dma_handle`과 `size`로 partial sync를 수행할 수 있습니다.
다음 시점에는 반드시 synchronize해야 합니다.
- Device가 DMA로 쓴 값을 읽기 전에는 DMA_FROM_DEVICE direction을 사용합니다.
- DMA로 device에 보낼 값을 쓴 뒤에는 DMA_TO_DEVICE direction을 사용합니다.
- Memory가 DMA_BIDIRECTIONAL이면 device에 넘기기 전과 돌려받은 뒤 모두 수행합니다.
관련 규칙은 `dma_map_single()` 설명도 참고하십시오.
DMA attribute가 있는 mapping
414-477dma_addr_t
dma_map_single_attrs(struct device *dev, void *cpu_addr, size_t size,
enum dma_data_direction dir,
unsigned long attrs)
void
dma_unmap_single_attrs(struct device *dev, dma_addr_t dma_addr,
size_t size, enum dma_data_direction dir,
unsigned long attrs)
int
dma_map_sg_attrs(struct device *dev, struct scatterlist *sgl,
int nents, enum dma_data_direction dir,
unsigned long attrs)
void
dma_unmap_sg_attrs(struct device *dev, struct scatterlist *sgl,
int nents, enum dma_data_direction dir,
unsigned long attrs)
위 네 함수는 `_attrs` suffix가 없는 대응 함수와 같지만 optional `dma_attrs`를 추가로 전달합니다.
DMA attribute 해석은 architecture마다 다르며 각 attribute는 `Documentation/core-api/dma-attributes.rst`에 문서화해야 합니다.
`dma_attrs`가 0이면 각 함수의 의미는 `_attrs` 없는 대응 함수와 같습니다. 따라서 일반적으로 `dma_map_single_attrs()`가 `dma_map_single()`을 대체할 수 있습니다.
`*_attrs` 함수로 memory를 DMA mapping할 때 `DMA_ATTR_FOO` attribute를 전달하는 예는 다음과 같습니다.
#include <linux/dma-mapping.h>
/* DMA_ATTR_FOO should be defined in linux/dma-mapping.h and
* documented in Documentation/core-api/dma-attributes.rst */
...
unsigned long attr;
attr |= DMA_ATTR_FOO;
....
n = dma_map_sg_attrs(dev, sg, nents, DMA_TO_DEVICE, attr);
....
`DMA_ATTR_FOO`를 고려하는 architecture는 mapping 및 unmapping 구현에서 attribute 존재를 다음처럼 검사합니다.
void whizco_dma_map_sg_attrs(struct device *dev, dma_addr_t dma_addr,
size_t size, enum dma_data_direction dir,
unsigned long attrs)
{
....
if (attrs & DMA_ATTR_FOO)
/* twizzle the frobnozzle */
....
}
Part Ie IOVA 기반 DMA mapping
478-549Part Ie - IOVA-based DMA mapping
이 API는 IOMMU 사용 시 매우 효율적인 mapping을 제공합니다. 추가 code가 필요한 optional path이며 DMA mapping 성능이나 DMA address 저장 공간이 중요한 driver에만 권장합니다. 앞 절의 모든 고려 사항이 그대로 적용됩니다.
bool dma_iova_try_alloc(struct device *dev, struct dma_iova_state *state,
phys_addr_t phys, size_t size);
`dma_iova_try_alloc()`은 mapping operation을 위한 IOVA space allocation을 시도합니다. `false`면 해당 device에 이 API를 사용할 수 없으므로 일반 streaming DMA mapping API를 사용합니다. `struct dma_iova_state`는 driver가 allocate하고 unmap 때까지 유지해야 합니다.
static inline bool dma_use_iova(struct dma_iova_state *state)
`dma_use_iova()`는 `dma_iova_try_alloc()` 호출 뒤 IOVA 기반 API가 사용 중인지 driver가 확인합니다. Unmap path에서 유용합니다.
int dma_iova_link(struct device *dev, struct dma_iova_state *state,
phys_addr_t phys, size_t offset, size_t size,
enum dma_data_direction dir, unsigned long attrs);
`dma_iova_link()`는 앞서 allocate한 IOVA에 range를 연결합니다. 한 state에 대한 첫 호출을 제외한 모든 range 시작점은 `dma_get_merge_boundary()`가 반환한 DMA merge boundary에 맞춰야 하며 마지막을 제외한 모든 range size도 같은 boundary에 맞춰야 합니다.
int dma_iova_sync(struct device *dev, struct dma_iova_state *state,
size_t offset, size_t size);
`dma_iova_sync()`는 하나 이상의 `dma_iova_link()` 호출로 mapping한 IOVA range의 IOMMU page table을 synchronize하기 위해 호출해야 합니다.
One-shot mapping driver는 다음 함수로 모든 range를 unmap하고 IOVA를 free할 수 있습니다.
void dma_iova_destroy(struct device *dev, struct dma_iova_state *state,
size_t mapped_len, enum dma_data_direction dir,
unsigned long attrs);
또는 개별 region을 mapping/unmapping하여 IOVA space를 동적으로 관리할 수 있습니다. 앞서 mapping한 range는 다음으로 unmap합니다.
void dma_iova_unlink(struct device *dev, struct dma_iova_state *state,
size_t offset, size_t size, enum dma_data_direction dir,
unsigned long attrs);
IOVA space는 다음으로 free합니다.
void dma_iova_free(struct device *dev, struct dma_iova_state *state);
`dma_iova_free()` 호출 전에 모든 region을 `dma_iova_unlink()`로 unmap해야 합니다.
Part II non-coherent page allocation
550-626Part II - Non-coherent DMA allocation
이 API는 주어진 device가 DMA address로 접근할 수 있음을 보장하는 page를 allocate하지만 kernel과 device 사이의 memory ownership을 명시적으로 관리해야 합니다. Processor와 I/O device 사이의 cache line coherency를 이해하지 못한다면 이 API 부분을 사용하면 안 됩니다.
struct page *
dma_alloc_pages(struct device *dev, size_t size, dma_addr_t *dma_handle,
enum dma_data_direction dir, gfp_t gfp)
`dma_alloc_pages()`는 `size` byte의 non-coherent memory region을 allocate합니다. 성공하면 region의 첫 `struct page` pointer를, 실패하면 `NULL`을 반환합니다. 결과 page는 일반 `struct page` 용도에 사용할 수 있습니다. 함께 반환하는 `dma_handle`은 bus 폭의 unsigned integer로 cast하여 device에 region의 DMA address base로 전달할 수 있습니다.
`dir`은 device가 data를 읽거나 쓰는 방향이며 자세한 내용은 `dma_map_single()`을 참고합니다. `gfp`는 `kmalloc()`과 같은 `GFP_` flag를 지정하지만 `GFP_DMA`, `GFP_HIGHMEM`처럼 memory zone을 고르는 flag는 거부합니다.
Memory를 device에 넘기기 전에 `dma_sync_single_for_device()`를, device가 쓴 memory를 읽기 전에 `dma_sync_single_for_cpu()`를 호출해야 합니다. 재사용하는 streaming DMA mapping과 같은 규칙입니다.
void
dma_free_pages(struct device *dev, size_t size, struct page *page,
dma_addr_t dma_handle, enum dma_data_direction dir)
`dma_free_pages()`는 `dma_alloc_pages()`가 allocate한 memory를 free합니다. `dev`, `size`, `dma_handle`, `dir`은 allocation 때와 같아야 하고 `page`는 반환받은 pointer여야 합니다.
int
dma_mmap_pages(struct device *dev, struct vm_area_struct *vma,
size_t size, struct page *page)
`dma_mmap_pages()`는 `dma_alloc_pages()` allocation을 user address space에 mapping합니다. `dev`, `size`, `page`는 allocation 때 사용하거나 반환받은 값과 같아야 합니다.
void *
dma_alloc_noncoherent(struct device *dev, size_t size,
dma_addr_t *dma_handle, enum dma_data_direction dir,
gfp_t gfp)
`dma_alloc_noncoherent()`는 `dma_alloc_pages()`의 편의 wrapper로, page structure 대신 allocate한 memory의 kernel virtual address를 반환합니다.
void
dma_free_noncoherent(struct device *dev, size_t size, void *cpu_addr,
dma_addr_t dma_handle, enum dma_data_direction dir)
`dma_free_noncoherent()`는 앞 함수로 allocate한 memory를 free합니다. 모든 parameter는 allocation 때 전달하거나 반환받은 값과 같아야 합니다.
Non-contiguous allocation과 cache alignment
627-722struct sg_table *
dma_alloc_noncontiguous(struct device *dev, size_t size,
enum dma_data_direction dir, gfp_t gfp,
unsigned long attrs);
`dma_alloc_noncontiguous()`는 `size` byte의 non-coherent하고 물리적으로 연속되지 않을 수 있는 memory를 allocate합니다. 성공하면 allocate 및 DMA mapping된 memory를 설명하는 `struct sg_table` pointer를, 실패하면 `NULL`을 반환합니다.
반환 `sg_table`은 `sgt->nents` 기준으로 DMA mapped segment가 정확히 하나임을 보장하지만 CPU 쪽 segment는 `sgt->orig_nents`가 나타내듯 여러 개일 수 있습니다. `dir`과 `gfp` 규칙은 위와 같고 `attrs`는 0 또는 `DMA_ATTR_ALLOC_SINGLE_PAGES`여야 합니다.
Device에 넘기기 전에 `dma_sync_sgtable_for_device()`를, device가 쓴 memory를 읽기 전에 `dma_sync_sgtable_for_cpu()`를 호출합니다.
void
dma_free_noncontiguous(struct device *dev, size_t size,
struct sg_table *sgt,
enum dma_data_direction dir)
`dma_free_noncontiguous()`는 앞 함수가 allocate한 memory를 free합니다. `dev`, `size`, `dir`은 같아야 하고 `sgt`는 반환받은 pointer여야 합니다.
void *
dma_vmap_noncontiguous(struct device *dev, size_t size,
struct sg_table *sgt)
`dma_vmap_noncontiguous()`는 non-contiguous allocation에 대한 contiguous kernel mapping을 반환합니다. Mapping 뒤에는 `flush_kernel_vmap_range()`와 `invalidate_kernel_vmap_range()`를 사용해 kernel mapping, device, user space mapping 사이의 coherency를 관리해야 합니다.
void
dma_vunmap_noncontiguous(struct device *dev, void *vaddr)
`dma_vunmap_noncontiguous()`는 위 함수가 반환한 kernel mapping을 unmap합니다. `dev`는 allocation 때와 같고 `vaddr`는 반환받은 pointer여야 합니다.
int
dma_mmap_noncontiguous(struct device *dev, struct vm_area_struct *vma,
size_t size, struct sg_table *sgt)
`dma_mmap_noncontiguous()`는 non-contiguous allocation을 user address space에 mapping하며 `dev`, `size`, `sgt`는 allocation과 일치해야 합니다.
int
dma_get_cache_alignment(void)
`dma_get_cache_alignment()`는 processor cache alignment를 반환합니다. Memory mapping이나 partial flush에서 지켜야 할 절대 최소 alignment이자 width입니다.
이 API는 실제 cache line보다 큰 값을 반환할 수 있지만 하나 이상의 cache line이 반환 width에 정확히 들어맞음을 보장합니다. 쉽게 정렬할 수 있도록 항상 2의 거듭제곱입니다.
Part III DMA API 사용 오류 디버깅
723-781Part III - Driver의 DMA API 사용 디버깅
DMA API에는 같은 size와 대응 함수로 DMA address를 해제해야 하는 등의 제약이 있습니다. Hardware IOMMU가 보편화되면서 driver가 이를 지키는 일이 더 중요해졌고, 최악에는 filesystem 파괴까지 포함한 data corruption이 생길 수 있습니다.
DMA API 사용 bug를 찾기 위한 검사 code를 kernel에 compile할 수 있습니다. Architecture가 지원하면 kernel configuration에서 `Enable debugging of DMA API usage`를 선택합니다. 성능 영향이 있으므로 production kernel에서는 활성화하지 마십시오.
이 kernel은 어느 device에 어떤 DMA memory가 allocate되었는지 bookkeeping하고 오류를 발견하면 상세 warning을 kernel log에 출력합니다. 예시는 다음과 같습니다.
WARNING: at /data2/repos/linux-2.6-iommu/lib/dma-debug.c:448
check_unmap+0x203/0x490()
Hardware name:
forcedeth 0000:00:08.0: DMA-API: device driver frees DMA memory with wrong
function [device address=0x00000000640444be] [size=66 bytes] [mapped as
single] [unmapped as page]
Modules linked in: nfsd exportfs bridge stp llc r8169
Pid: 0, comm: swapper Tainted: G W 2.6.28-dmatest-09289-g8bb99c0 #1
Call Trace:
<IRQ> [<ffffffff80240b22>] warn_slowpath+0xf2/0x130
[<ffffffff80647b70>] _spin_unlock+0x10/0x30
[<ffffffff80537e75>] usb_hcd_link_urb_to_ep+0x75/0xc0
[<ffffffff80647c22>] _spin_unlock_irqrestore+0x12/0x40
[<ffffffff8055347f>] ohci_urb_enqueue+0x19f/0x7c0
[<ffffffff80252f96>] queue_work+0x56/0x60
[<ffffffff80237e10>] enqueue_task_fair+0x20/0x50
[<ffffffff80539279>] usb_hcd_submit_urb+0x379/0xbc0
[<ffffffff803b78c3>] cpumask_next_and+0x23/0x40
[<ffffffff80235177>] find_busiest_group+0x207/0x8a0
[<ffffffff8064784f>] _spin_lock_irqsave+0x1f/0x50
[<ffffffff803c7ea3>] check_unmap+0x203/0x490
[<ffffffff803c8259>] debug_dma_unmap_phys+0x49/0x50
[<ffffffff80485f26>] nv_tx_done_optimized+0xc6/0x2c0
[<ffffffff80486c13>] nv_nic_irq_optimized+0x73/0x2b0
[<ffffffff8026df84>] handle_IRQ_event+0x34/0x70
[<ffffffff8026ffe9>] handle_edge_irq+0xc9/0x150
[<ffffffff8020e3ab>] do_IRQ+0xcb/0x1c0
[<ffffffff8020c093>] ret_from_intr+0x0/0xa
<EOI> <4>---[ end trace f6435a98e2a38c0e ]---
Driver developer는 warning을 발생시킨 DMA API 호출의 stack trace와 함께 driver와 device를 찾을 수 있습니다.
기본적으로 첫 오류만 warning message를 만들고 나머지는 조용히 count합니다. Kernel log flooding을 막기 위한 제한이며 driver debugging 중에는 아래 debugfs interface로 해제할 수 있습니다.
DMA API debugfs interface와 boot parameter
782-849DMA API debugging code의 debugfs directory는 `dma-api/`이며 다음 file을 제공합니다.
| 파일 | 설명 |
|---|---|
| dma-api/all_errors | 0이 아니면 발견한 모든 오류를 kernel log에 warning으로 출력합니다. Log flooding에 주의해야 합니다. |
| dma-api/disabled | Debug code가 memory 부족이나 boot 설정으로 비활성화되었으면 읽기 전용 값 Y를 표시합니다. |
| dma-api/dump | 현재 DMA mapping을 보여 주는 읽기 전용 file입니다. |
| dma-api/error_count | 발견된 전체 오류 수를 보여 주는 읽기 전용 file입니다. |
| dma-api/num_errors | Kernel log에 출력할 warning 수입니다. Boot 때 1이며 값을 쓸 수 있습니다. |
| dma-api/min_free_entries | Allocator가 관측한 최소 free dma_debug_entries 수입니다. 0이면 nr_total_entries 증가를 시도합니다. |
| dma-api/num_free_entries | Allocator의 현재 free dma_debug_entries 수입니다. |
| dma-api/nr_total_entries | Free 및 사용 중 entry를 합한 전체 dma_debug_entries 수입니다. |
| dma-api/driver_filter | 특정 driver 이름을 써서 debug output을 제한합니다. 빈 문자열을 쓰면 filter를 끄고 모든 오류를 다시 봅니다. |
Code를 kernel에 compile하면 기본 활성화됩니다. Bookkeeping 없이 부팅하려면 `dma_debug=off` boot parameter를 사용합니다. Runtime에는 다시 활성화할 수 없으므로 reboot해야 합니다.
특정 device driver의 debug message만 보려면 `dma_debug_driver=<drivername>` parameter를 사용합니다. Boot 때 driver filter를 활성화하며 이후 debugfs에서 끄거나 바꿀 수 있습니다.
Runtime에 code가 스스로 비활성화되었다면 보통 `dma_debug_entries`가 바닥나 추가 allocate에 실패한 경우입니다. Boot 때 65536개를 preallocate하며 부족하면 `dma_debug_entries=<your_desired_number>`로 기본값을 덮어씁니다. Entry는 batch로 allocate하므로 실제 preallocation 수가 요청보다 클 수 있습니다. 동적 allocation 누계가 최초 preallocation만큼 늘 때마다 kernel log에 알리며, 더 큰 사전 할당이 필요하거나 계속 반복된다면 driver가 mapping을 leak할 수 있음을 뜻합니다.
Mapping 오류 검사 누락 탐지
850-863void
debug_dma_mapping_error(struct device *dev, dma_addr_t dma_addr);
`debug_dma_mapping_error()`는 `dma_map_single()`과 `dma_map_page()` 반환 주소의 DMA mapping error 검사를 빠뜨린 driver를 디버깅합니다. `debug_dma_map_phys()`가 설정한 flag를 지워 driver가 `dma_mapping_error()`를 호출했음을 표시합니다. Unmap 때 `debug_dma_unmap()`이 flag를 검사하고 그대로 남아 있으면 unmap까지 이어진 call trace를 포함한 warning을 출력합니다. DMA mapping error check debugging을 활성화하도록 `dma_mapping_error()` routine에서 호출할 수 있습니다.
함수와 구조체
864-868함수와 구조체
공개 함수와 structure의 kernel-doc은 `include/linux/scatterlist.h`와 `lib/scatterlist.c`에서 가져옵니다.
요약과 해설
dma-api.rst:1-868이 문서는 Linux generic device DMA API의 기준 명세입니다. Driver는 `dma_addr_t`를 CPU address처럼 직접 사용하지 않고, device DMA mask와 mapping size 한계를 설정한 뒤 각 allocate/map 함수의 반환값을 검사해야 합니다.
일반 driver는 Part I의 coherent, streaming, scatter/gather, attribute, IOVA API를 사용합니다. Non-coherent platform을 반드시 지원하는 경우에만 Part II의 explicit ownership API를 사용하며, cache line 경계와 CPU/device synchronization 규칙을 엄격히 지켜야 합니다.
Part III의 DMA API debugging은 잘못된 함수나 size로 unmap하는 오류, mapping error 검사 누락, mapping leak를 추적합니다. Production kernel에는 성능 비용 때문에 활성화하지 않으며 debugfs와 boot parameter로 출력 범위 및 entry 수를 조정합니다.