0001 =========================
0002 Dynamic DMA mapping Guide
0003 =========================
0004
0005 :Author: David S. Miller <davem@redhat.com>
0006 :Author: Richard Henderson <rth@cygnus.com>
0007 :Author: Jakub Jelinek <jakub@redhat.com>
0008
0009 This is a guide to device driver writers on how to use the DMA API
0010 with example pseudo-code. For a concise description of the API, see
0011 DMA-API.txt.
0012
0013 CPU and DMA addresses
0014 =====================
0015
0016 There are several kinds of addresses involved in the DMA API, and it's
0017 important to understand the differences.
0018
0019 The kernel normally uses virtual addresses. Any address returned by
0020 kmalloc(), vmalloc(), and similar interfaces is a virtual address and can
0021 be stored in a ``void *``.
0022
0023 The virtual memory system (TLB, page tables, etc.) translates virtual
0024 addresses to CPU physical addresses, which are stored as "phys_addr_t" or
0025 "resource_size_t". The kernel manages device resources like registers as
0026 physical addresses. These are the addresses in /proc/iomem. The physical
0027 address is not directly useful to a driver; it must use ioremap() to map
0028 the space and produce a virtual address.
0029
0030 I/O devices use a third kind of address: a "bus address". If a device has
0031 registers at an MMIO address, or if it performs DMA to read or write system
0032 memory, the addresses used by the device are bus addresses. In some
0033 systems, bus addresses are identical to CPU physical addresses, but in
0034 general they are not. IOMMUs and host bridges can produce arbitrary
0035 mappings between physical and bus addresses.
0036
0037 From a device's point of view, DMA uses the bus address space, but it may
0038 be restricted to a subset of that space. For example, even if a system
0039 supports 64-bit addresses for main memory and PCI BARs, it may use an IOMMU
0040 so devices only need to use 32-bit DMA addresses.
0041
0042 Here's a picture and some examples::
0043
0044 CPU CPU Bus
0045 Virtual Physical Address
0046 Address Address Space
0047 Space Space
0048
0049 +-------+ +------+ +------+
0050 | | |MMIO | Offset | |
0051 | | Virtual |Space | applied | |
0052 C +-------+ --------> B +------+ ----------> +------+ A
0053 | | mapping | | by host | |
0054 +-----+ | | | | bridge | | +--------+
0055 | | | | +------+ | | | |
0056 | CPU | | | | RAM | | | | Device |
0057 | | | | | | | | | |
0058 +-----+ +-------+ +------+ +------+ +--------+
0059 | | Virtual |Buffer| Mapping | |
0060 X +-------+ --------> Y +------+ <---------- +------+ Z
0061 | | mapping | RAM | by IOMMU
0062 | | | |
0063 | | | |
0064 +-------+ +------+
0065
0066 During the enumeration process, the kernel learns about I/O devices and
0067 their MMIO space and the host bridges that connect them to the system. For
0068 example, if a PCI device has a BAR, the kernel reads the bus address (A)
0069 from the BAR and converts it to a CPU physical address (B). The address B
0070 is stored in a struct resource and usually exposed via /proc/iomem. When a
0071 driver claims a device, it typically uses ioremap() to map physical address
0072 B at a virtual address (C). It can then use, e.g., ioread32(C), to access
0073 the device registers at bus address A.
0074
0075 If the device supports DMA, the driver sets up a buffer using kmalloc() or
0076 a similar interface, which returns a virtual address (X). The virtual
0077 memory system maps X to a physical address (Y) in system RAM. The driver
0078 can use virtual address X to access the buffer, but the device itself
0079 cannot because DMA doesn't go through the CPU virtual memory system.
0080
0081 In some simple systems, the device can do DMA directly to physical address
0082 Y. But in many others, there is IOMMU hardware that translates DMA
0083 addresses to physical addresses, e.g., it translates Z to Y. This is part
0084 of the reason for the DMA API: the driver can give a virtual address X to
0085 an interface like dma_map_single(), which sets up any required IOMMU
0086 mapping and returns the DMA address Z. The driver then tells the device to
0087 do DMA to Z, and the IOMMU maps it to the buffer at address Y in system
0088 RAM.
0089
0090 So that Linux can use the dynamic DMA mapping, it needs some help from the
0091 drivers, namely it has to take into account that DMA addresses should be
0092 mapped only for the time they are actually used and unmapped after the DMA
0093 transfer.
0094
0095 The following API will work of course even on platforms where no such
0096 hardware exists.
0097
0098 Note that the DMA API works with any bus independent of the underlying
0099 microprocessor architecture. You should use the DMA API rather than the
0100 bus-specific DMA API, i.e., use the dma_map_*() interfaces rather than the
0101 pci_map_*() interfaces.
0102
0103 First of all, you should make sure::
0104
0105 #include <linux/dma-mapping.h>
0106
0107 is in your driver, which provides the definition of dma_addr_t. This type
0108 can hold any valid DMA address for the platform and should be used
0109 everywhere you hold a DMA address returned from the DMA mapping functions.
0110
0111 What memory is DMA'able?
0112 ========================
0113
0114 The first piece of information you must know is what kernel memory can
0115 be used with the DMA mapping facilities. There has been an unwritten
0116 set of rules regarding this, and this text is an attempt to finally
0117 write them down.
0118
0119 If you acquired your memory via the page allocator
0120 (i.e. __get_free_page*()) or the generic memory allocators
0121 (i.e. kmalloc() or kmem_cache_alloc()) then you may DMA to/from
0122 that memory using the addresses returned from those routines.
0123
0124 This means specifically that you may _not_ use the memory/addresses
0125 returned from vmalloc() for DMA. It is possible to DMA to the
0126 _underlying_ memory mapped into a vmalloc() area, but this requires
0127 walking page tables to get the physical addresses, and then
0128 translating each of those pages back to a kernel address using
0129 something like __va(). [ EDIT: Update this when we integrate
0130 Gerd Knorr's generic code which does this. ]
0131
0132 This rule also means that you may use neither kernel image addresses
0133 (items in data/text/bss segments), nor module image addresses, nor
0134 stack addresses for DMA. These could all be mapped somewhere entirely
0135 different than the rest of physical memory. Even if those classes of
0136 memory could physically work with DMA, you'd need to ensure the I/O
0137 buffers were cacheline-aligned. Without that, you'd see cacheline
0138 sharing problems (data corruption) on CPUs with DMA-incoherent caches.
0139 (The CPU could write to one word, DMA would write to a different one
0140 in the same cache line, and one of them could be overwritten.)
0141
0142 Also, this means that you cannot take the return of a kmap()
0143 call and DMA to/from that. This is similar to vmalloc().
0144
0145 What about block I/O and networking buffers? The block I/O and
0146 networking subsystems make sure that the buffers they use are valid
0147 for you to DMA from/to.
0148
0149 DMA addressing capabilities
0150 ===========================
0151
0152 By default, the kernel assumes that your device can address 32-bits of DMA
0153 addressing. For a 64-bit capable device, this needs to be increased, and for
0154 a device with limitations, it needs to be decreased.
0155
0156 Special note about PCI: PCI-X specification requires PCI-X devices to support
0157 64-bit addressing (DAC) for all transactions. And at least one platform (SGI
0158 SN2) requires 64-bit consistent allocations to operate correctly when the IO
0159 bus is in PCI-X mode.
0160
0161 For correct operation, you must set the DMA mask to inform the kernel about
0162 your devices DMA addressing capabilities.
0163
0164 This is performed via a call to dma_set_mask_and_coherent()::
0165
0166 int dma_set_mask_and_coherent(struct device *dev, u64 mask);
0167
0168 which will set the mask for both streaming and coherent APIs together. If you
0169 have some special requirements, then the following two separate calls can be
0170 used instead:
0171
0172 The setup for streaming mappings is performed via a call to
0173 dma_set_mask()::
0174
0175 int dma_set_mask(struct device *dev, u64 mask);
0176
0177 The setup for consistent allocations is performed via a call
0178 to dma_set_coherent_mask()::
0179
0180 int dma_set_coherent_mask(struct device *dev, u64 mask);
0181
0182 Here, dev is a pointer to the device struct of your device, and mask is a bit
0183 mask describing which bits of an address your device supports. Often the
0184 device struct of your device is embedded in the bus-specific device struct of
0185 your device. For example, &pdev->dev is a pointer to the device struct of a
0186 PCI device (pdev is a pointer to the PCI device struct of your device).
0187
0188 These calls usually return zero to indicated your device can perform DMA
0189 properly on the machine given the address mask you provided, but they might
0190 return an error if the mask is too small to be supportable on the given
0191 system. If it returns non-zero, your device cannot perform DMA properly on
0192 this platform, and attempting to do so will result in undefined behavior.
0193 You must not use DMA on this device unless the dma_set_mask family of
0194 functions has returned success.
0195
0196 This means that in the failure case, you have two options:
0197
0198 1) Use some non-DMA mode for data transfer, if possible.
0199 2) Ignore this device and do not initialize it.
0200
0201 It is recommended that your driver print a kernel KERN_WARNING message when
0202 setting the DMA mask fails. In this manner, if a user of your driver reports
0203 that performance is bad or that the device is not even detected, you can ask
0204 them for the kernel messages to find out exactly why.
0205
0206 The standard 64-bit addressing device would do something like this::
0207
0208 if (dma_set_mask_and_coherent(dev, DMA_BIT_MASK(64))) {
0209 dev_warn(dev, "mydev: No suitable DMA available\n");
0210 goto ignore_this_device;
0211 }
0212
0213 If the device only supports 32-bit addressing for descriptors in the
0214 coherent allocations, but supports full 64-bits for streaming mappings
0215 it would look like this::
0216
0217 if (dma_set_mask(dev, DMA_BIT_MASK(64))) {
0218 dev_warn(dev, "mydev: No suitable DMA available\n");
0219 goto ignore_this_device;
0220 }
0221
0222 The coherent mask will always be able to set the same or a smaller mask as
0223 the streaming mask. However for the rare case that a device driver only
0224 uses consistent allocations, one would have to check the return value from
0225 dma_set_coherent_mask().
0226
0227 Finally, if your device can only drive the low 24-bits of
0228 address you might do something like::
0229
0230 if (dma_set_mask(dev, DMA_BIT_MASK(24))) {
0231 dev_warn(dev, "mydev: 24-bit DMA addressing not available\n");
0232 goto ignore_this_device;
0233 }
0234
0235 When dma_set_mask() or dma_set_mask_and_coherent() is successful, and
0236 returns zero, the kernel saves away this mask you have provided. The
0237 kernel will use this information later when you make DMA mappings.
0238
0239 There is a case which we are aware of at this time, which is worth
0240 mentioning in this documentation. If your device supports multiple
0241 functions (for example a sound card provides playback and record
0242 functions) and the various different functions have _different_
0243 DMA addressing limitations, you may wish to probe each mask and
0244 only provide the functionality which the machine can handle. It
0245 is important that the last call to dma_set_mask() be for the
0246 most specific mask.
0247
0248 Here is pseudo-code showing how this might be done::
0249
0250 #define PLAYBACK_ADDRESS_BITS DMA_BIT_MASK(32)
0251 #define RECORD_ADDRESS_BITS DMA_BIT_MASK(24)
0252
0253 struct my_sound_card *card;
0254 struct device *dev;
0255
0256 ...
0257 if (!dma_set_mask(dev, PLAYBACK_ADDRESS_BITS)) {
0258 card->playback_enabled = 1;
0259 } else {
0260 card->playback_enabled = 0;
0261 dev_warn(dev, "%s: Playback disabled due to DMA limitations\n",
0262 card->name);
0263 }
0264 if (!dma_set_mask(dev, RECORD_ADDRESS_BITS)) {
0265 card->record_enabled = 1;
0266 } else {
0267 card->record_enabled = 0;
0268 dev_warn(dev, "%s: Record disabled due to DMA limitations\n",
0269 card->name);
0270 }
0271
0272 A sound card was used as an example here because this genre of PCI
0273 devices seems to be littered with ISA chips given a PCI front end,
0274 and thus retaining the 16MB DMA addressing limitations of ISA.
0275
0276 Types of DMA mappings
0277 =====================
0278
0279 There are two types of DMA mappings:
0280
0281 - Consistent DMA mappings which are usually mapped at driver
0282 initialization, unmapped at the end and for which the hardware should
0283 guarantee that the device and the CPU can access the data
0284 in parallel and will see updates made by each other without any
0285 explicit software flushing.
0286
0287 Think of "consistent" as "synchronous" or "coherent".
0288
0289 The current default is to return consistent memory in the low 32
0290 bits of the DMA space. However, for future compatibility you should
0291 set the consistent mask even if this default is fine for your
0292 driver.
0293
0294 Good examples of what to use consistent mappings for are:
0295
0296 - Network card DMA ring descriptors.
0297 - SCSI adapter mailbox command data structures.
0298 - Device firmware microcode executed out of
0299 main memory.
0300
0301 The invariant these examples all require is that any CPU store
0302 to memory is immediately visible to the device, and vice
0303 versa. Consistent mappings guarantee this.
0304
0305 .. important::
0306
0307 Consistent DMA memory does not preclude the usage of
0308 proper memory barriers. The CPU may reorder stores to
0309 consistent memory just as it may normal memory. Example:
0310 if it is important for the device to see the first word
0311 of a descriptor updated before the second, you must do
0312 something like::
0313
0314 desc->word0 = address;
0315 wmb();
0316 desc->word1 = DESC_VALID;
0317
0318 in order to get correct behavior on all platforms.
0319
0320 Also, on some platforms your driver may need to flush CPU write
0321 buffers in much the same way as it needs to flush write buffers
0322 found in PCI bridges (such as by reading a register's value
0323 after writing it).
0324
0325 - Streaming DMA mappings which are usually mapped for one DMA
0326 transfer, unmapped right after it (unless you use dma_sync_* below)
0327 and for which hardware can optimize for sequential accesses.
0328
0329 Think of "streaming" as "asynchronous" or "outside the coherency
0330 domain".
0331
0332 Good examples of what to use streaming mappings for are:
0333
0334 - Networking buffers transmitted/received by a device.
0335 - Filesystem buffers written/read by a SCSI device.
0336
0337 The interfaces for using this type of mapping were designed in
0338 such a way that an implementation can make whatever performance
0339 optimizations the hardware allows. To this end, when using
0340 such mappings you must be explicit about what you want to happen.
0341
0342 Neither type of DMA mapping has alignment restrictions that come from
0343 the underlying bus, although some devices may have such restrictions.
0344 Also, systems with caches that aren't DMA-coherent will work better
0345 when the underlying buffers don't share cache lines with other data.
0346
0347
0348 Using Consistent DMA mappings
0349 =============================
0350
0351 To allocate and map large (PAGE_SIZE or so) consistent DMA regions,
0352 you should do::
0353
0354 dma_addr_t dma_handle;
0355
0356 cpu_addr = dma_alloc_coherent(dev, size, &dma_handle, gfp);
0357
0358 where device is a ``struct device *``. This may be called in interrupt
0359 context with the GFP_ATOMIC flag.
0360
0361 Size is the length of the region you want to allocate, in bytes.
0362
0363 This routine will allocate RAM for that region, so it acts similarly to
0364 __get_free_pages() (but takes size instead of a page order). If your
0365 driver needs regions sized smaller than a page, you may prefer using
0366 the dma_pool interface, described below.
0367
0368 The consistent DMA mapping interfaces, will by default return a DMA address
0369 which is 32-bit addressable. Even if the device indicates (via the DMA mask)
0370 that it may address the upper 32-bits, consistent allocation will only
0371 return > 32-bit addresses for DMA if the consistent DMA mask has been
0372 explicitly changed via dma_set_coherent_mask(). This is true of the
0373 dma_pool interface as well.
0374
0375 dma_alloc_coherent() returns two values: the virtual address which you
0376 can use to access it from the CPU and dma_handle which you pass to the
0377 card.
0378
0379 The CPU virtual address and the DMA address are both
0380 guaranteed to be aligned to the smallest PAGE_SIZE order which
0381 is greater than or equal to the requested size. This invariant
0382 exists (for example) to guarantee that if you allocate a chunk
0383 which is smaller than or equal to 64 kilobytes, the extent of the
0384 buffer you receive will not cross a 64K boundary.
0385
0386 To unmap and free such a DMA region, you call::
0387
0388 dma_free_coherent(dev, size, cpu_addr, dma_handle);
0389
0390 where dev, size are the same as in the above call and cpu_addr and
0391 dma_handle are the values dma_alloc_coherent() returned to you.
0392 This function may not be called in interrupt context.
0393
0394 If your driver needs lots of smaller memory regions, you can write
0395 custom code to subdivide pages returned by dma_alloc_coherent(),
0396 or you can use the dma_pool API to do that. A dma_pool is like
0397 a kmem_cache, but it uses dma_alloc_coherent(), not __get_free_pages().
0398 Also, it understands common hardware constraints for alignment,
0399 like queue heads needing to be aligned on N byte boundaries.
0400
0401 Create a dma_pool like this::
0402
0403 struct dma_pool *pool;
0404
0405 pool = dma_pool_create(name, dev, size, align, boundary);
0406
0407 The "name" is for diagnostics (like a kmem_cache name); dev and size
0408 are as above. The device's hardware alignment requirement for this
0409 type of data is "align" (which is expressed in bytes, and must be a
0410 power of two). If your device has no boundary crossing restrictions,
0411 pass 0 for boundary; passing 4096 says memory allocated from this pool
0412 must not cross 4KByte boundaries (but at that time it may be better to
0413 use dma_alloc_coherent() directly instead).
0414
0415 Allocate memory from a DMA pool like this::
0416
0417 cpu_addr = dma_pool_alloc(pool, flags, &dma_handle);
0418
0419 flags are GFP_KERNEL if blocking is permitted (not in_interrupt nor
0420 holding SMP locks), GFP_ATOMIC otherwise. Like dma_alloc_coherent(),
0421 this returns two values, cpu_addr and dma_handle.
0422
0423 Free memory that was allocated from a dma_pool like this::
0424
0425 dma_pool_free(pool, cpu_addr, dma_handle);
0426
0427 where pool is what you passed to dma_pool_alloc(), and cpu_addr and
0428 dma_handle are the values dma_pool_alloc() returned. This function
0429 may be called in interrupt context.
0430
0431 Destroy a dma_pool by calling::
0432
0433 dma_pool_destroy(pool);
0434
0435 Make sure you've called dma_pool_free() for all memory allocated
0436 from a pool before you destroy the pool. This function may not
0437 be called in interrupt context.
0438
0439 DMA Direction
0440 =============
0441
0442 The interfaces described in subsequent portions of this document
0443 take a DMA direction argument, which is an integer and takes on
0444 one of the following values::
0445
0446 DMA_BIDIRECTIONAL
0447 DMA_TO_DEVICE
0448 DMA_FROM_DEVICE
0449 DMA_NONE
0450
0451 You should provide the exact DMA direction if you know it.
0452
0453 DMA_TO_DEVICE means "from main memory to the device"
0454 DMA_FROM_DEVICE means "from the device to main memory"
0455 It is the direction in which the data moves during the DMA
0456 transfer.
0457
0458 You are _strongly_ encouraged to specify this as precisely
0459 as you possibly can.
0460
0461 If you absolutely cannot know the direction of the DMA transfer,
0462 specify DMA_BIDIRECTIONAL. It means that the DMA can go in
0463 either direction. The platform guarantees that you may legally
0464 specify this, and that it will work, but this may be at the
0465 cost of performance for example.
0466
0467 The value DMA_NONE is to be used for debugging. One can
0468 hold this in a data structure before you come to know the
0469 precise direction, and this will help catch cases where your
0470 direction tracking logic has failed to set things up properly.
0471
0472 Another advantage of specifying this value precisely (outside of
0473 potential platform-specific optimizations of such) is for debugging.
0474 Some platforms actually have a write permission boolean which DMA
0475 mappings can be marked with, much like page protections in the user
0476 program address space. Such platforms can and do report errors in the
0477 kernel logs when the DMA controller hardware detects violation of the
0478 permission setting.
0479
0480 Only streaming mappings specify a direction, consistent mappings
0481 implicitly have a direction attribute setting of
0482 DMA_BIDIRECTIONAL.
0483
0484 The SCSI subsystem tells you the direction to use in the
0485 'sc_data_direction' member of the SCSI command your driver is
0486 working on.
0487
0488 For Networking drivers, it's a rather simple affair. For transmit
0489 packets, map/unmap them with the DMA_TO_DEVICE direction
0490 specifier. For receive packets, just the opposite, map/unmap them
0491 with the DMA_FROM_DEVICE direction specifier.
0492
0493 Using Streaming DMA mappings
0494 ============================
0495
0496 The streaming DMA mapping routines can be called from interrupt
0497 context. There are two versions of each map/unmap, one which will
0498 map/unmap a single memory region, and one which will map/unmap a
0499 scatterlist.
0500
0501 To map a single region, you do::
0502
0503 struct device *dev = &my_dev->dev;
0504 dma_addr_t dma_handle;
0505 void *addr = buffer->ptr;
0506 size_t size = buffer->len;
0507
0508 dma_handle = dma_map_single(dev, addr, size, direction);
0509 if (dma_mapping_error(dev, dma_handle)) {
0510 /*
0511 * reduce current DMA mapping usage,
0512 * delay and try again later or
0513 * reset driver.
0514 */
0515 goto map_error_handling;
0516 }
0517
0518 and to unmap it::
0519
0520 dma_unmap_single(dev, dma_handle, size, direction);
0521
0522 You should call dma_mapping_error() as dma_map_single() could fail and return
0523 error. Doing so will ensure that the mapping code will work correctly on all
0524 DMA implementations without any dependency on the specifics of the underlying
0525 implementation. Using the returned address without checking for errors could
0526 result in failures ranging from panics to silent data corruption. The same
0527 applies to dma_map_page() as well.
0528
0529 You should call dma_unmap_single() when the DMA activity is finished, e.g.,
0530 from the interrupt which told you that the DMA transfer is done.
0531
0532 Using CPU pointers like this for single mappings has a disadvantage:
0533 you cannot reference HIGHMEM memory in this way. Thus, there is a
0534 map/unmap interface pair akin to dma_{map,unmap}_single(). These
0535 interfaces deal with page/offset pairs instead of CPU pointers.
0536 Specifically::
0537
0538 struct device *dev = &my_dev->dev;
0539 dma_addr_t dma_handle;
0540 struct page *page = buffer->page;
0541 unsigned long offset = buffer->offset;
0542 size_t size = buffer->len;
0543
0544 dma_handle = dma_map_page(dev, page, offset, size, direction);
0545 if (dma_mapping_error(dev, dma_handle)) {
0546 /*
0547 * reduce current DMA mapping usage,
0548 * delay and try again later or
0549 * reset driver.
0550 */
0551 goto map_error_handling;
0552 }
0553
0554 ...
0555
0556 dma_unmap_page(dev, dma_handle, size, direction);
0557
0558 Here, "offset" means byte offset within the given page.
0559
0560 You should call dma_mapping_error() as dma_map_page() could fail and return
0561 error as outlined under the dma_map_single() discussion.
0562
0563 You should call dma_unmap_page() when the DMA activity is finished, e.g.,
0564 from the interrupt which told you that the DMA transfer is done.
0565
0566 With scatterlists, you map a region gathered from several regions by::
0567
0568 int i, count = dma_map_sg(dev, sglist, nents, direction);
0569 struct scatterlist *sg;
0570
0571 for_each_sg(sglist, sg, count, i) {
0572 hw_address[i] = sg_dma_address(sg);
0573 hw_len[i] = sg_dma_len(sg);
0574 }
0575
0576 where nents is the number of entries in the sglist.
0577
0578 The implementation is free to merge several consecutive sglist entries
0579 into one (e.g. if DMA mapping is done with PAGE_SIZE granularity, any
0580 consecutive sglist entries can be merged into one provided the first one
0581 ends and the second one starts on a page boundary - in fact this is a huge
0582 advantage for cards which either cannot do scatter-gather or have very
0583 limited number of scatter-gather entries) and returns the actual number
0584 of sg entries it mapped them to. On failure 0 is returned.
0585
0586 Then you should loop count times (note: this can be less than nents times)
0587 and use sg_dma_address() and sg_dma_len() macros where you previously
0588 accessed sg->address and sg->length as shown above.
0589
0590 To unmap a scatterlist, just call::
0591
0592 dma_unmap_sg(dev, sglist, nents, direction);
0593
0594 Again, make sure DMA activity has already finished.
0595
0596 .. note::
0597
0598 The 'nents' argument to the dma_unmap_sg call must be
0599 the _same_ one you passed into the dma_map_sg call,
0600 it should _NOT_ be the 'count' value _returned_ from the
0601 dma_map_sg call.
0602
0603 Every dma_map_{single,sg}() call should have its dma_unmap_{single,sg}()
0604 counterpart, because the DMA address space is a shared resource and
0605 you could render the machine unusable by consuming all DMA addresses.
0606
0607 If you need to use the same streaming DMA region multiple times and touch
0608 the data in between the DMA transfers, the buffer needs to be synced
0609 properly in order for the CPU and device to see the most up-to-date and
0610 correct copy of the DMA buffer.
0611
0612 So, firstly, just map it with dma_map_{single,sg}(), and after each DMA
0613 transfer call either::
0614
0615 dma_sync_single_for_cpu(dev, dma_handle, size, direction);
0616
0617 or::
0618
0619 dma_sync_sg_for_cpu(dev, sglist, nents, direction);
0620
0621 as appropriate.
0622
0623 Then, if you wish to let the device get at the DMA area again,
0624 finish accessing the data with the CPU, and then before actually
0625 giving the buffer to the hardware call either::
0626
0627 dma_sync_single_for_device(dev, dma_handle, size, direction);
0628
0629 or::
0630
0631 dma_sync_sg_for_device(dev, sglist, nents, direction);
0632
0633 as appropriate.
0634
0635 .. note::
0636
0637 The 'nents' argument to dma_sync_sg_for_cpu() and
0638 dma_sync_sg_for_device() must be the same passed to
0639 dma_map_sg(). It is _NOT_ the count returned by
0640 dma_map_sg().
0641
0642 After the last DMA transfer call one of the DMA unmap routines
0643 dma_unmap_{single,sg}(). If you don't touch the data from the first
0644 dma_map_*() call till dma_unmap_*(), then you don't have to call the
0645 dma_sync_*() routines at all.
0646
0647 Here is pseudo code which shows a situation in which you would need
0648 to use the dma_sync_*() interfaces::
0649
0650 my_card_setup_receive_buffer(struct my_card *cp, char *buffer, int len)
0651 {
0652 dma_addr_t mapping;
0653
0654 mapping = dma_map_single(cp->dev, buffer, len, DMA_FROM_DEVICE);
0655 if (dma_mapping_error(cp->dev, mapping)) {
0656 /*
0657 * reduce current DMA mapping usage,
0658 * delay and try again later or
0659 * reset driver.
0660 */
0661 goto map_error_handling;
0662 }
0663
0664 cp->rx_buf = buffer;
0665 cp->rx_len = len;
0666 cp->rx_dma = mapping;
0667
0668 give_rx_buf_to_card(cp);
0669 }
0670
0671 ...
0672
0673 my_card_interrupt_handler(int irq, void *devid, struct pt_regs *regs)
0674 {
0675 struct my_card *cp = devid;
0676
0677 ...
0678 if (read_card_status(cp) == RX_BUF_TRANSFERRED) {
0679 struct my_card_header *hp;
0680
0681 /* Examine the header to see if we wish
0682 * to accept the data. But synchronize
0683 * the DMA transfer with the CPU first
0684 * so that we see updated contents.
0685 */
0686 dma_sync_single_for_cpu(&cp->dev, cp->rx_dma,
0687 cp->rx_len,
0688 DMA_FROM_DEVICE);
0689
0690 /* Now it is safe to examine the buffer. */
0691 hp = (struct my_card_header *) cp->rx_buf;
0692 if (header_is_ok(hp)) {
0693 dma_unmap_single(&cp->dev, cp->rx_dma, cp->rx_len,
0694 DMA_FROM_DEVICE);
0695 pass_to_upper_layers(cp->rx_buf);
0696 make_and_setup_new_rx_buf(cp);
0697 } else {
0698 /* CPU should not write to
0699 * DMA_FROM_DEVICE-mapped area,
0700 * so dma_sync_single_for_device() is
0701 * not needed here. It would be required
0702 * for DMA_BIDIRECTIONAL mapping if
0703 * the memory was modified.
0704 */
0705 give_rx_buf_to_card(cp);
0706 }
0707 }
0708 }
0709
0710 Handling Errors
0711 ===============
0712
0713 DMA address space is limited on some architectures and an allocation
0714 failure can be determined by:
0715
0716 - checking if dma_alloc_coherent() returns NULL or dma_map_sg returns 0
0717
0718 - checking the dma_addr_t returned from dma_map_single() and dma_map_page()
0719 by using dma_mapping_error()::
0720
0721 dma_addr_t dma_handle;
0722
0723 dma_handle = dma_map_single(dev, addr, size, direction);
0724 if (dma_mapping_error(dev, dma_handle)) {
0725 /*
0726 * reduce current DMA mapping usage,
0727 * delay and try again later or
0728 * reset driver.
0729 */
0730 goto map_error_handling;
0731 }
0732
0733 - unmap pages that are already mapped, when mapping error occurs in the middle
0734 of a multiple page mapping attempt. These example are applicable to
0735 dma_map_page() as well.
0736
0737 Example 1::
0738
0739 dma_addr_t dma_handle1;
0740 dma_addr_t dma_handle2;
0741
0742 dma_handle1 = dma_map_single(dev, addr, size, direction);
0743 if (dma_mapping_error(dev, dma_handle1)) {
0744 /*
0745 * reduce current DMA mapping usage,
0746 * delay and try again later or
0747 * reset driver.
0748 */
0749 goto map_error_handling1;
0750 }
0751 dma_handle2 = dma_map_single(dev, addr, size, direction);
0752 if (dma_mapping_error(dev, dma_handle2)) {
0753 /*
0754 * reduce current DMA mapping usage,
0755 * delay and try again later or
0756 * reset driver.
0757 */
0758 goto map_error_handling2;
0759 }
0760
0761 ...
0762
0763 map_error_handling2:
0764 dma_unmap_single(dma_handle1);
0765 map_error_handling1:
0766
0767 Example 2::
0768
0769 /*
0770 * if buffers are allocated in a loop, unmap all mapped buffers when
0771 * mapping error is detected in the middle
0772 */
0773
0774 dma_addr_t dma_addr;
0775 dma_addr_t array[DMA_BUFFERS];
0776 int save_index = 0;
0777
0778 for (i = 0; i < DMA_BUFFERS; i++) {
0779
0780 ...
0781
0782 dma_addr = dma_map_single(dev, addr, size, direction);
0783 if (dma_mapping_error(dev, dma_addr)) {
0784 /*
0785 * reduce current DMA mapping usage,
0786 * delay and try again later or
0787 * reset driver.
0788 */
0789 goto map_error_handling;
0790 }
0791 array[i].dma_addr = dma_addr;
0792 save_index++;
0793 }
0794
0795 ...
0796
0797 map_error_handling:
0798
0799 for (i = 0; i < save_index; i++) {
0800
0801 ...
0802
0803 dma_unmap_single(array[i].dma_addr);
0804 }
0805
0806 Networking drivers must call dev_kfree_skb() to free the socket buffer
0807 and return NETDEV_TX_OK if the DMA mapping fails on the transmit hook
0808 (ndo_start_xmit). This means that the socket buffer is just dropped in
0809 the failure case.
0810
0811 SCSI drivers must return SCSI_MLQUEUE_HOST_BUSY if the DMA mapping
0812 fails in the queuecommand hook. This means that the SCSI subsystem
0813 passes the command to the driver again later.
0814
0815 Optimizing Unmap State Space Consumption
0816 ========================================
0817
0818 On many platforms, dma_unmap_{single,page}() is simply a nop.
0819 Therefore, keeping track of the mapping address and length is a waste
0820 of space. Instead of filling your drivers up with ifdefs and the like
0821 to "work around" this (which would defeat the whole purpose of a
0822 portable API) the following facilities are provided.
0823
0824 Actually, instead of describing the macros one by one, we'll
0825 transform some example code.
0826
0827 1) Use DEFINE_DMA_UNMAP_{ADDR,LEN} in state saving structures.
0828 Example, before::
0829
0830 struct ring_state {
0831 struct sk_buff *skb;
0832 dma_addr_t mapping;
0833 __u32 len;
0834 };
0835
0836 after::
0837
0838 struct ring_state {
0839 struct sk_buff *skb;
0840 DEFINE_DMA_UNMAP_ADDR(mapping);
0841 DEFINE_DMA_UNMAP_LEN(len);
0842 };
0843
0844 2) Use dma_unmap_{addr,len}_set() to set these values.
0845 Example, before::
0846
0847 ringp->mapping = FOO;
0848 ringp->len = BAR;
0849
0850 after::
0851
0852 dma_unmap_addr_set(ringp, mapping, FOO);
0853 dma_unmap_len_set(ringp, len, BAR);
0854
0855 3) Use dma_unmap_{addr,len}() to access these values.
0856 Example, before::
0857
0858 dma_unmap_single(dev, ringp->mapping, ringp->len,
0859 DMA_FROM_DEVICE);
0860
0861 after::
0862
0863 dma_unmap_single(dev,
0864 dma_unmap_addr(ringp, mapping),
0865 dma_unmap_len(ringp, len),
0866 DMA_FROM_DEVICE);
0867
0868 It really should be self-explanatory. We treat the ADDR and LEN
0869 separately, because it is possible for an implementation to only
0870 need the address in order to perform the unmap operation.
0871
0872 Platform Issues
0873 ===============
0874
0875 If you are just writing drivers for Linux and do not maintain
0876 an architecture port for the kernel, you can safely skip down
0877 to "Closing".
0878
0879 1) Struct scatterlist requirements.
0880
0881 You need to enable CONFIG_NEED_SG_DMA_LENGTH if the architecture
0882 supports IOMMUs (including software IOMMU).
0883
0884 2) ARCH_DMA_MINALIGN
0885
0886 Architectures must ensure that kmalloc'ed buffer is
0887 DMA-safe. Drivers and subsystems depend on it. If an architecture
0888 isn't fully DMA-coherent (i.e. hardware doesn't ensure that data in
0889 the CPU cache is identical to data in main memory),
0890 ARCH_DMA_MINALIGN must be set so that the memory allocator
0891 makes sure that kmalloc'ed buffer doesn't share a cache line with
0892 the others. See arch/arm/include/asm/cache.h as an example.
0893
0894 Note that ARCH_DMA_MINALIGN is about DMA memory alignment
0895 constraints. You don't need to worry about the architecture data
0896 alignment constraints (e.g. the alignment constraints about 64-bit
0897 objects).
0898
0899 Closing
0900 =======
0901
0902 This document, and the API itself, would not be in its current
0903 form without the feedback and suggestions from numerous individuals.
0904 We would like to specifically mention, in no particular order, the
0905 following people::
0906
0907 Russell King <rmk@arm.linux.org.uk>
0908 Leo Dagum <dagum@barrel.engr.sgi.com>
0909 Ralf Baechle <ralf@oss.sgi.com>
0910 Grant Grundler <grundler@cup.hp.com>
0911 Jay Estabrook <Jay.Estabrook@compaq.com>
0912 Thomas Sailer <sailer@ife.ee.ethz.ch>
0913 Andrea Arcangeli <andrea@suse.de>
0914 Jens Axboe <jens.axboe@oracle.com>
0915 David Mosberger-Tang <davidm@hpl.hp.com>