dma-api-howto.rst 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. =========================
  2. Dynamic DMA mapping Guide
  3. =========================
  4. :Author: David S. Miller <davem@redhat.com>
  5. :Author: Richard Henderson <rth@cygnus.com>
  6. :Author: Jakub Jelinek <jakub@redhat.com>
  7. This is a guide to device driver writers on how to use the DMA API
  8. with example pseudo-code. For a concise description of the API, see
  9. Documentation/core-api/dma-api.rst.
  10. CPU and DMA addresses
  11. =====================
  12. There are several kinds of addresses involved in the DMA API, and it's
  13. important to understand the differences.
  14. The kernel normally uses virtual addresses. Any address returned by
  15. kmalloc(), vmalloc(), and similar interfaces is a virtual address and can
  16. be stored in a ``void *``.
  17. The virtual memory system (TLB, page tables, etc.) translates virtual
  18. addresses to CPU physical addresses, which are stored as "phys_addr_t" or
  19. "resource_size_t". The kernel manages device resources like registers as
  20. physical addresses. These are the addresses in /proc/iomem. The physical
  21. address is not directly useful to a driver; it must use ioremap() to map
  22. the space and produce a virtual address.
  23. I/O devices use a third kind of address: a "bus address". If a device has
  24. registers at an MMIO address, or if it performs DMA to read or write system
  25. memory, the addresses used by the device are bus addresses. In some
  26. systems, bus addresses are identical to CPU physical addresses, but in
  27. general they are not. IOMMUs and host bridges can produce arbitrary
  28. mappings between physical and bus addresses.
  29. From a device's point of view, DMA uses the bus address space, but it may
  30. be restricted to a subset of that space. For example, even if a system
  31. supports 64-bit addresses for main memory and PCI BARs, it may use an IOMMU
  32. so devices only need to use 32-bit DMA addresses.
  33. Here's a picture and some examples::
  34. CPU CPU Bus
  35. Virtual Physical Address
  36. Address Address Space
  37. Space Space
  38. +-------+ +------+ +------+
  39. | | |MMIO | Offset | |
  40. | | Virtual |Space | applied | |
  41. C +-------+ --------> B +------+ ----------> +------+ A
  42. | | mapping | | by host | |
  43. +-----+ | | | | bridge | | +--------+
  44. | | | | +------+ | | | |
  45. | CPU | | | | RAM | | | | Device |
  46. | | | | | | | | | |
  47. +-----+ +-------+ +------+ +------+ +--------+
  48. | | Virtual |Buffer| Mapping | |
  49. X +-------+ --------> Y +------+ <---------- +------+ Z
  50. | | mapping | RAM | by IOMMU
  51. | | | |
  52. | | | |
  53. +-------+ +------+
  54. During the enumeration process, the kernel learns about I/O devices and
  55. their MMIO space and the host bridges that connect them to the system. For
  56. example, if a PCI device has a BAR, the kernel reads the bus address (A)
  57. from the BAR and converts it to a CPU physical address (B). The address B
  58. is stored in a struct resource and usually exposed via /proc/iomem. When a
  59. driver claims a device, it typically uses ioremap() to map physical address
  60. B at a virtual address (C). It can then use, e.g., ioread32(C), to access
  61. the device registers at bus address A.
  62. If the device supports DMA, the driver sets up a buffer using kmalloc() or
  63. a similar interface, which returns a virtual address (X). The virtual
  64. memory system maps X to a physical address (Y) in system RAM. The driver
  65. can use virtual address X to access the buffer, but the device itself
  66. cannot because DMA doesn't go through the CPU virtual memory system.
  67. In some simple systems, the device can do DMA directly to physical address
  68. Y. But in many others, there is IOMMU hardware that translates DMA
  69. addresses to physical addresses, e.g., it translates Z to Y. This is part
  70. of the reason for the DMA API: the driver can give a virtual address X to
  71. an interface like dma_map_single(), which sets up any required IOMMU
  72. mapping and returns the DMA address Z. The driver then tells the device to
  73. do DMA to Z, and the IOMMU maps it to the buffer at address Y in system
  74. RAM.
  75. So that Linux can use the dynamic DMA mapping, it needs some help from the
  76. drivers, namely it has to take into account that DMA addresses should be
  77. mapped only for the time they are actually used and unmapped after the DMA
  78. transfer.
  79. The following API will work of course even on platforms where no such
  80. hardware exists.
  81. Note that the DMA API works with any bus independent of the underlying
  82. microprocessor architecture. You should use the DMA API rather than the
  83. bus-specific DMA API, i.e., use the dma_map_*() interfaces rather than the
  84. pci_map_*() interfaces.
  85. First of all, you should make sure::
  86. #include <linux/dma-mapping.h>
  87. is in your driver, which provides the definition of dma_addr_t. This type
  88. can hold any valid DMA address for the platform and should be used
  89. everywhere you hold a DMA address returned from the DMA mapping functions.
  90. What memory is DMA'able?
  91. ========================
  92. The first piece of information you must know is what kernel memory can
  93. be used with the DMA mapping facilities. There has been an unwritten
  94. set of rules regarding this, and this text is an attempt to finally
  95. write them down.
  96. If you acquired your memory via the page allocator
  97. (i.e. __get_free_page*()) or the generic memory allocators
  98. (i.e. kmalloc() or kmem_cache_alloc()) then you may DMA to/from
  99. that memory using the addresses returned from those routines.
  100. This means specifically that you may _not_ use the memory/addresses
  101. returned from vmalloc() for DMA. It is possible to DMA to the
  102. _underlying_ memory mapped into a vmalloc() area, but this requires
  103. walking page tables to get the physical addresses, and then
  104. translating each of those pages back to a kernel address using
  105. something like __va(). [ EDIT: Update this when we integrate
  106. Gerd Knorr's generic code which does this. ]
  107. This rule also means that you may use neither kernel image addresses
  108. (items in data/text/bss segments), nor module image addresses, nor
  109. stack addresses for DMA. These could all be mapped somewhere entirely
  110. different than the rest of physical memory. Even if those classes of
  111. memory could physically work with DMA, you'd need to ensure the I/O
  112. buffers were cacheline-aligned. Without that, you'd see cacheline
  113. sharing problems (data corruption) on CPUs with DMA-incoherent caches.
  114. (The CPU could write to one word, DMA would write to a different one
  115. in the same cache line, and one of them could be overwritten.)
  116. Also, this means that you cannot take the return of a kmap()
  117. call and DMA to/from that. This is similar to vmalloc().
  118. What about block I/O and networking buffers? The block I/O and
  119. networking subsystems make sure that the buffers they use are valid
  120. for you to DMA from/to.
  121. __dma_from_device_group_begin/end annotations
  122. =============================================
  123. As explained previously, when a structure contains a DMA_FROM_DEVICE /
  124. DMA_BIDIRECTIONAL buffer (device writes to memory) alongside fields that the
  125. CPU writes to, cache line sharing between the DMA buffer and CPU-written fields
  126. can cause data corruption on CPUs with DMA-incoherent caches.
  127. The ``__dma_from_device_group_begin(GROUP)/__dma_from_device_group_end(GROUP)``
  128. macros ensure proper alignment to prevent this::
  129. struct my_device {
  130. spinlock_t lock1;
  131. __dma_from_device_group_begin();
  132. char dma_buffer1[16];
  133. char dma_buffer2[16];
  134. __dma_from_device_group_end();
  135. spinlock_t lock2;
  136. };
  137. To isolate a DMA buffer from adjacent fields, use
  138. ``__dma_from_device_group_begin(GROUP)`` before the first DMA buffer
  139. field and ``__dma_from_device_group_end(GROUP)`` after the last DMA
  140. buffer field (with the same GROUP name). This protects both the head
  141. and tail of the buffer from cache line sharing.
  142. The GROUP parameter is an optional identifier that names the DMA buffer group
  143. (in case you have several in the same structure)::
  144. struct my_device {
  145. spinlock_t lock1;
  146. __dma_from_device_group_begin(buffer1);
  147. char dma_buffer1[16];
  148. __dma_from_device_group_end(buffer1);
  149. spinlock_t lock2;
  150. __dma_from_device_group_begin(buffer2);
  151. char dma_buffer2[16];
  152. __dma_from_device_group_end(buffer2);
  153. };
  154. On cache-coherent platforms these macros expand to zero-length array markers.
  155. On non-coherent platforms, they also ensure the minimal DMA alignment, which
  156. can be as large as 128 bytes.
  157. .. note::
  158. It is allowed (though somewhat fragile) to include extra fields, not
  159. intended for DMA from the device, within the group (in order to pack the
  160. structure tightly) - but only as long as the CPU does not write these
  161. fields while any fields in the group are mapped for DMA_FROM_DEVICE or
  162. DMA_BIDIRECTIONAL.
  163. DMA addressing capabilities
  164. ===========================
  165. By default, the kernel assumes that your device can address 32-bits of DMA
  166. addressing. For a 64-bit capable device, this needs to be increased, and for
  167. a device with limitations, it needs to be decreased.
  168. Special note about PCI: PCI-X specification requires PCI-X devices to support
  169. 64-bit addressing (DAC) for all transactions. And at least one platform (SGI
  170. SN2) requires 64-bit coherent allocations to operate correctly when the IO
  171. bus is in PCI-X mode.
  172. For correct operation, you must set the DMA mask to inform the kernel about
  173. your devices DMA addressing capabilities.
  174. This is performed via a call to dma_set_mask_and_coherent()::
  175. int dma_set_mask_and_coherent(struct device *dev, u64 mask);
  176. which will set the mask for both streaming and coherent APIs together. If you
  177. have some special requirements, then the following two separate calls can be
  178. used instead:
  179. The setup for streaming mappings is performed via a call to
  180. dma_set_mask()::
  181. int dma_set_mask(struct device *dev, u64 mask);
  182. The setup for coherent allocations is performed via a call
  183. to dma_set_coherent_mask()::
  184. int dma_set_coherent_mask(struct device *dev, u64 mask);
  185. Here, dev is a pointer to the device struct of your device, and mask is a bit
  186. mask describing which bits of an address your device supports. Often the
  187. device struct of your device is embedded in the bus-specific device struct of
  188. your device. For example, &pdev->dev is a pointer to the device struct of a
  189. PCI device (pdev is a pointer to the PCI device struct of your device).
  190. These calls usually return zero to indicate your device can perform DMA
  191. properly on the machine given the address mask you provided, but they might
  192. return an error if the mask is too small to be supportable on the given
  193. system. If it returns non-zero, your device cannot perform DMA properly on
  194. this platform, and attempting to do so will result in undefined behavior.
  195. You must not use DMA on this device unless the dma_set_mask family of
  196. functions has returned success.
  197. This means that in the failure case, you have two options:
  198. 1) Use some non-DMA mode for data transfer, if possible.
  199. 2) Ignore this device and do not initialize it.
  200. It is recommended that your driver print a kernel KERN_WARNING message when
  201. setting the DMA mask fails. In this manner, if a user of your driver reports
  202. that performance is bad or that the device is not even detected, you can ask
  203. them for the kernel messages to find out exactly why.
  204. The 24-bit addressing device would do something like this::
  205. if (dma_set_mask_and_coherent(dev, DMA_BIT_MASK(24))) {
  206. dev_warn(dev, "mydev: No suitable DMA available\n");
  207. goto ignore_this_device;
  208. }
  209. The standard 64-bit addressing device would do something like this::
  210. dma_set_mask_and_coherent(dev, DMA_BIT_MASK(64))
  211. dma_set_mask_and_coherent() never return fail when DMA_BIT_MASK(64). Typical
  212. error code like::
  213. /* Wrong code */
  214. if (dma_set_mask_and_coherent(dev, DMA_BIT_MASK(64)))
  215. dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32))
  216. dma_set_mask_and_coherent() will never return failure when bigger than 32.
  217. So typical code like::
  218. /* Recommended code */
  219. if (support_64bit)
  220. dma_set_mask_and_coherent(dev, DMA_BIT_MASK(64));
  221. else
  222. dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32));
  223. If the device only supports 32-bit addressing for descriptors in the
  224. coherent allocations, but supports full 64-bits for streaming mappings
  225. it would look like this::
  226. if (dma_set_mask(dev, DMA_BIT_MASK(64))) {
  227. dev_warn(dev, "mydev: No suitable DMA available\n");
  228. goto ignore_this_device;
  229. }
  230. The coherent mask will always be able to set the same or a smaller mask as
  231. the streaming mask. However for the rare case that a device driver only
  232. uses coherent allocations, one would have to check the return value from
  233. dma_set_coherent_mask().
  234. Finally, if your device can only drive the low 24-bits of
  235. address you might do something like::
  236. if (dma_set_mask(dev, DMA_BIT_MASK(24))) {
  237. dev_warn(dev, "mydev: 24-bit DMA addressing not available\n");
  238. goto ignore_this_device;
  239. }
  240. When dma_set_mask() or dma_set_mask_and_coherent() is successful, and
  241. returns zero, the kernel saves away this mask you have provided. The
  242. kernel will use this information later when you make DMA mappings.
  243. There is a case which we are aware of at this time, which is worth
  244. mentioning in this documentation. If your device supports multiple
  245. functions (for example a sound card provides playback and record
  246. functions) and the various different functions have _different_
  247. DMA addressing limitations, you may wish to probe each mask and
  248. only provide the functionality which the machine can handle. It
  249. is important that the last call to dma_set_mask() be for the
  250. most specific mask.
  251. Here is pseudo-code showing how this might be done::
  252. #define PLAYBACK_ADDRESS_BITS DMA_BIT_MASK(32)
  253. #define RECORD_ADDRESS_BITS DMA_BIT_MASK(24)
  254. struct my_sound_card *card;
  255. struct device *dev;
  256. ...
  257. if (!dma_set_mask(dev, PLAYBACK_ADDRESS_BITS)) {
  258. card->playback_enabled = 1;
  259. } else {
  260. card->playback_enabled = 0;
  261. dev_warn(dev, "%s: Playback disabled due to DMA limitations\n",
  262. card->name);
  263. }
  264. if (!dma_set_mask(dev, RECORD_ADDRESS_BITS)) {
  265. card->record_enabled = 1;
  266. } else {
  267. card->record_enabled = 0;
  268. dev_warn(dev, "%s: Record disabled due to DMA limitations\n",
  269. card->name);
  270. }
  271. A sound card was used as an example here because this genre of PCI
  272. devices seems to be littered with ISA chips given a PCI front end,
  273. and thus retaining the 16MB DMA addressing limitations of ISA.
  274. Types of DMA mappings
  275. =====================
  276. There are two types of DMA mappings:
  277. - Coherent DMA mappings which are usually mapped at driver
  278. initialization, unmapped at the end and for which the hardware should
  279. guarantee that the device and the CPU can access the data
  280. in parallel and will see updates made by each other without any
  281. explicit software flushing.
  282. Think of "coherent" as "synchronous".
  283. The current default is to return coherent memory in the low 32
  284. bits of the DMA space. However, for future compatibility you should
  285. set the coherent mask even if this default is fine for your
  286. driver.
  287. Good examples of what to use coherent mappings for are:
  288. - Network card DMA ring descriptors.
  289. - SCSI adapter mailbox command data structures.
  290. - Device firmware microcode executed out of
  291. main memory.
  292. The invariant these examples all require is that any CPU store
  293. to memory is immediately visible to the device, and vice
  294. versa. Coherent mappings guarantee this.
  295. .. important::
  296. Coherent DMA memory does not preclude the usage of
  297. proper memory barriers. The CPU may reorder stores to
  298. coherent memory just as it may normal memory. Example:
  299. if it is important for the device to see the first word
  300. of a descriptor updated before the second, you must do
  301. something like::
  302. desc->word0 = address;
  303. wmb();
  304. desc->word1 = DESC_VALID;
  305. in order to get correct behavior on all platforms.
  306. Also, on some platforms your driver may need to flush CPU write
  307. buffers in much the same way as it needs to flush write buffers
  308. found in PCI bridges (such as by reading a register's value
  309. after writing it).
  310. - Streaming DMA mappings which are usually mapped for one DMA
  311. transfer, unmapped right after it (unless you use dma_sync_* below)
  312. and for which hardware can optimize for sequential accesses.
  313. Think of "streaming" as "asynchronous" or "outside the coherency
  314. domain".
  315. Good examples of what to use streaming mappings for are:
  316. - Networking buffers transmitted/received by a device.
  317. - Filesystem buffers written/read by a SCSI device.
  318. The interfaces for using this type of mapping were designed in
  319. such a way that an implementation can make whatever performance
  320. optimizations the hardware allows. To this end, when using
  321. such mappings you must be explicit about what you want to happen.
  322. Neither type of DMA mapping has alignment restrictions that come from
  323. the underlying bus, although some devices may have such restrictions.
  324. Also, systems with caches that aren't DMA-coherent will work better
  325. when the underlying buffers don't share cache lines with other data.
  326. Using Coherent DMA mappings
  327. ===========================
  328. To allocate and map large (PAGE_SIZE or so) coherent DMA regions,
  329. you should do::
  330. dma_addr_t dma_handle;
  331. cpu_addr = dma_alloc_coherent(dev, size, &dma_handle, gfp);
  332. where device is a ``struct device *``. This may be called in interrupt
  333. context with the GFP_ATOMIC flag.
  334. Size is the length of the region you want to allocate, in bytes.
  335. This routine will allocate RAM for that region, so it acts similarly to
  336. __get_free_pages() (but takes size instead of a page order). If your
  337. driver needs regions sized smaller than a page, you may prefer using
  338. the dma_pool interface, described below.
  339. The coherent DMA mapping interfaces, will by default return a DMA address
  340. which is 32-bit addressable. Even if the device indicates (via the DMA mask)
  341. that it may address the upper 32-bits, coherent allocation will only
  342. return > 32-bit addresses for DMA if the coherent DMA mask has been
  343. explicitly changed via dma_set_coherent_mask(). This is true of the
  344. dma_pool interface as well.
  345. dma_alloc_coherent() returns two values: the virtual address which you
  346. can use to access it from the CPU and dma_handle which you pass to the
  347. card.
  348. The CPU virtual address and the DMA address are both
  349. guaranteed to be aligned to the smallest PAGE_SIZE order which
  350. is greater than or equal to the requested size. This invariant
  351. exists (for example) to guarantee that if you allocate a chunk
  352. which is smaller than or equal to 64 kilobytes, the extent of the
  353. buffer you receive will not cross a 64K boundary.
  354. To unmap and free such a DMA region, you call::
  355. dma_free_coherent(dev, size, cpu_addr, dma_handle);
  356. where dev, size are the same as in the above call and cpu_addr and
  357. dma_handle are the values dma_alloc_coherent() returned to you.
  358. This function may not be called in interrupt context.
  359. If your driver needs lots of smaller memory regions, you can write
  360. custom code to subdivide pages returned by dma_alloc_coherent(),
  361. or you can use the dma_pool API to do that. A dma_pool is like
  362. a kmem_cache, but it uses dma_alloc_coherent(), not __get_free_pages().
  363. Also, it understands common hardware constraints for alignment,
  364. like queue heads needing to be aligned on N byte boundaries.
  365. Create a dma_pool like this::
  366. struct dma_pool *pool;
  367. pool = dma_pool_create(name, dev, size, align, boundary);
  368. The "name" is for diagnostics (like a kmem_cache name); dev and size
  369. are as above. The device's hardware alignment requirement for this
  370. type of data is "align" (which is expressed in bytes, and must be a
  371. power of two). If your device has no boundary crossing restrictions,
  372. pass 0 for boundary; passing 4096 says memory allocated from this pool
  373. must not cross 4KByte boundaries (but at that time it may be better to
  374. use dma_alloc_coherent() directly instead).
  375. Allocate memory from a DMA pool like this::
  376. cpu_addr = dma_pool_alloc(pool, flags, &dma_handle);
  377. flags are GFP_KERNEL if blocking is permitted (not in_interrupt nor
  378. holding SMP locks), GFP_ATOMIC otherwise. Like dma_alloc_coherent(),
  379. this returns two values, cpu_addr and dma_handle.
  380. Free memory that was allocated from a dma_pool like this::
  381. dma_pool_free(pool, cpu_addr, dma_handle);
  382. where pool is what you passed to dma_pool_alloc(), and cpu_addr and
  383. dma_handle are the values dma_pool_alloc() returned. This function
  384. may be called in interrupt context.
  385. Destroy a dma_pool by calling::
  386. dma_pool_destroy(pool);
  387. Make sure you've called dma_pool_free() for all memory allocated
  388. from a pool before you destroy the pool. This function may not
  389. be called in interrupt context.
  390. DMA Direction
  391. =============
  392. The interfaces described in subsequent portions of this document
  393. take a DMA direction argument, which is an integer and takes on
  394. one of the following values::
  395. DMA_BIDIRECTIONAL
  396. DMA_TO_DEVICE
  397. DMA_FROM_DEVICE
  398. DMA_NONE
  399. You should provide the exact DMA direction if you know it.
  400. DMA_TO_DEVICE means "from main memory to the device"
  401. DMA_FROM_DEVICE means "from the device to main memory"
  402. It is the direction in which the data moves during the DMA
  403. transfer.
  404. You are _strongly_ encouraged to specify this as precisely
  405. as you possibly can.
  406. If you absolutely cannot know the direction of the DMA transfer,
  407. specify DMA_BIDIRECTIONAL. It means that the DMA can go in
  408. either direction. The platform guarantees that you may legally
  409. specify this, and that it will work, but this may be at the
  410. cost of performance for example.
  411. The value DMA_NONE is to be used for debugging. One can
  412. hold this in a data structure before you come to know the
  413. precise direction, and this will help catch cases where your
  414. direction tracking logic has failed to set things up properly.
  415. Another advantage of specifying this value precisely (outside of
  416. potential platform-specific optimizations of such) is for debugging.
  417. Some platforms actually have a write permission boolean which DMA
  418. mappings can be marked with, much like page protections in the user
  419. program address space. Such platforms can and do report errors in the
  420. kernel logs when the DMA controller hardware detects violation of the
  421. permission setting.
  422. Only streaming mappings specify a direction, coherent mappings
  423. implicitly have a direction attribute setting of
  424. DMA_BIDIRECTIONAL.
  425. The SCSI subsystem tells you the direction to use in the
  426. 'sc_data_direction' member of the SCSI command your driver is
  427. working on.
  428. For Networking drivers, it's a rather simple affair. For transmit
  429. packets, map/unmap them with the DMA_TO_DEVICE direction
  430. specifier. For receive packets, just the opposite, map/unmap them
  431. with the DMA_FROM_DEVICE direction specifier.
  432. Using Streaming DMA mappings
  433. ============================
  434. The streaming DMA mapping routines can be called from interrupt
  435. context. There are two versions of each map/unmap, one which will
  436. map/unmap a single memory region, and one which will map/unmap a
  437. scatterlist.
  438. To map a single region, you do::
  439. struct device *dev = &my_dev->dev;
  440. dma_addr_t dma_handle;
  441. void *addr = buffer->ptr;
  442. size_t size = buffer->len;
  443. dma_handle = dma_map_single(dev, addr, size, direction);
  444. if (dma_mapping_error(dev, dma_handle)) {
  445. /*
  446. * reduce current DMA mapping usage,
  447. * delay and try again later or
  448. * reset driver.
  449. */
  450. goto map_error_handling;
  451. }
  452. and to unmap it::
  453. dma_unmap_single(dev, dma_handle, size, direction);
  454. You should call dma_mapping_error() as dma_map_single() could fail and return
  455. error. Doing so will ensure that the mapping code will work correctly on all
  456. DMA implementations without any dependency on the specifics of the underlying
  457. implementation. Using the returned address without checking for errors could
  458. result in failures ranging from panics to silent data corruption. The same
  459. applies to dma_map_page() as well.
  460. You should call dma_unmap_single() when the DMA activity is finished, e.g.,
  461. from the interrupt which told you that the DMA transfer is done.
  462. Using CPU pointers like this for single mappings has a disadvantage:
  463. you cannot reference HIGHMEM memory in this way. Thus, there is a
  464. map/unmap interface pair akin to dma_{map,unmap}_single(). These
  465. interfaces deal with page/offset pairs instead of CPU pointers.
  466. Specifically::
  467. struct device *dev = &my_dev->dev;
  468. dma_addr_t dma_handle;
  469. struct page *page = buffer->page;
  470. unsigned long offset = buffer->offset;
  471. size_t size = buffer->len;
  472. dma_handle = dma_map_page(dev, page, offset, size, direction);
  473. if (dma_mapping_error(dev, dma_handle)) {
  474. /*
  475. * reduce current DMA mapping usage,
  476. * delay and try again later or
  477. * reset driver.
  478. */
  479. goto map_error_handling;
  480. }
  481. ...
  482. dma_unmap_page(dev, dma_handle, size, direction);
  483. Here, "offset" means byte offset within the given page.
  484. You should call dma_mapping_error() as dma_map_page() could fail and return
  485. error as outlined under the dma_map_single() discussion.
  486. You should call dma_unmap_page() when the DMA activity is finished, e.g.,
  487. from the interrupt which told you that the DMA transfer is done.
  488. With scatterlists, you map a region gathered from several regions by::
  489. int i, count = dma_map_sg(dev, sglist, nents, direction);
  490. struct scatterlist *sg;
  491. for_each_sg(sglist, sg, count, i) {
  492. hw_address[i] = sg_dma_address(sg);
  493. hw_len[i] = sg_dma_len(sg);
  494. }
  495. where nents is the number of entries in the sglist.
  496. The implementation is free to merge several consecutive sglist entries
  497. into one (e.g. if DMA mapping is done with PAGE_SIZE granularity, any
  498. consecutive sglist entries can be merged into one provided the first one
  499. ends and the second one starts on a page boundary - in fact this is a huge
  500. advantage for cards which either cannot do scatter-gather or have very
  501. limited number of scatter-gather entries) and returns the actual number
  502. of sg entries it mapped them to. On failure 0 is returned.
  503. Then you should loop count times (note: this can be less than nents times)
  504. and use sg_dma_address() and sg_dma_len() macros where you previously
  505. accessed sg->address and sg->length as shown above.
  506. To unmap a scatterlist, just call::
  507. dma_unmap_sg(dev, sglist, nents, direction);
  508. Again, make sure DMA activity has already finished.
  509. .. note::
  510. The 'nents' argument to the dma_unmap_sg call must be
  511. the _same_ one you passed into the dma_map_sg call,
  512. it should _NOT_ be the 'count' value _returned_ from the
  513. dma_map_sg call.
  514. Every dma_map_{single,sg}() call should have its dma_unmap_{single,sg}()
  515. counterpart, because the DMA address space is a shared resource and
  516. you could render the machine unusable by consuming all DMA addresses.
  517. If you need to use the same streaming DMA region multiple times and touch
  518. the data in between the DMA transfers, the buffer needs to be synced
  519. properly in order for the CPU and device to see the most up-to-date and
  520. correct copy of the DMA buffer.
  521. So, firstly, just map it with dma_map_{single,sg}(), and after each DMA
  522. transfer call either::
  523. dma_sync_single_for_cpu(dev, dma_handle, size, direction);
  524. or::
  525. dma_sync_sg_for_cpu(dev, sglist, nents, direction);
  526. as appropriate.
  527. Then, if you wish to let the device get at the DMA area again,
  528. finish accessing the data with the CPU, and then before actually
  529. giving the buffer to the hardware call either::
  530. dma_sync_single_for_device(dev, dma_handle, size, direction);
  531. or::
  532. dma_sync_sg_for_device(dev, sglist, nents, direction);
  533. as appropriate.
  534. .. note::
  535. The 'nents' argument to dma_sync_sg_for_cpu() and
  536. dma_sync_sg_for_device() must be the same passed to
  537. dma_map_sg(). It is _NOT_ the count returned by
  538. dma_map_sg().
  539. After the last DMA transfer call one of the DMA unmap routines
  540. dma_unmap_{single,sg}(). If you don't touch the data from the first
  541. dma_map_*() call till dma_unmap_*(), then you don't have to call the
  542. dma_sync_*() routines at all.
  543. Here is pseudo code which shows a situation in which you would need
  544. to use the dma_sync_*() interfaces::
  545. my_card_setup_receive_buffer(struct my_card *cp, char *buffer, int len)
  546. {
  547. dma_addr_t mapping;
  548. mapping = dma_map_single(cp->dev, buffer, len, DMA_FROM_DEVICE);
  549. if (dma_mapping_error(cp->dev, mapping)) {
  550. /*
  551. * reduce current DMA mapping usage,
  552. * delay and try again later or
  553. * reset driver.
  554. */
  555. goto map_error_handling;
  556. }
  557. cp->rx_buf = buffer;
  558. cp->rx_len = len;
  559. cp->rx_dma = mapping;
  560. give_rx_buf_to_card(cp);
  561. }
  562. ...
  563. my_card_interrupt_handler(int irq, void *devid, struct pt_regs *regs)
  564. {
  565. struct my_card *cp = devid;
  566. ...
  567. if (read_card_status(cp) == RX_BUF_TRANSFERRED) {
  568. struct my_card_header *hp;
  569. /* Examine the header to see if we wish
  570. * to accept the data. But synchronize
  571. * the DMA transfer with the CPU first
  572. * so that we see updated contents.
  573. */
  574. dma_sync_single_for_cpu(&cp->dev, cp->rx_dma,
  575. cp->rx_len,
  576. DMA_FROM_DEVICE);
  577. /* Now it is safe to examine the buffer. */
  578. hp = (struct my_card_header *) cp->rx_buf;
  579. if (header_is_ok(hp)) {
  580. dma_unmap_single(&cp->dev, cp->rx_dma, cp->rx_len,
  581. DMA_FROM_DEVICE);
  582. pass_to_upper_layers(cp->rx_buf);
  583. make_and_setup_new_rx_buf(cp);
  584. } else {
  585. /* CPU should not write to
  586. * DMA_FROM_DEVICE-mapped area,
  587. * so dma_sync_single_for_device() is
  588. * not needed here. It would be required
  589. * for DMA_BIDIRECTIONAL mapping if
  590. * the memory was modified.
  591. */
  592. give_rx_buf_to_card(cp);
  593. }
  594. }
  595. }
  596. Handling Errors
  597. ===============
  598. DMA address space is limited on some architectures and an allocation
  599. failure can be determined by:
  600. - checking if dma_alloc_coherent() returns NULL or dma_map_sg returns 0
  601. - checking the dma_addr_t returned from dma_map_single() and dma_map_page()
  602. by using dma_mapping_error()::
  603. dma_addr_t dma_handle;
  604. dma_handle = dma_map_single(dev, addr, size, direction);
  605. if (dma_mapping_error(dev, dma_handle)) {
  606. /*
  607. * reduce current DMA mapping usage,
  608. * delay and try again later or
  609. * reset driver.
  610. */
  611. goto map_error_handling;
  612. }
  613. - unmap pages that are already mapped, when mapping error occurs in the middle
  614. of a multiple page mapping attempt. These example are applicable to
  615. dma_map_page() as well.
  616. Example 1::
  617. dma_addr_t dma_handle1;
  618. dma_addr_t dma_handle2;
  619. dma_handle1 = dma_map_single(dev, addr, size, direction);
  620. if (dma_mapping_error(dev, dma_handle1)) {
  621. /*
  622. * reduce current DMA mapping usage,
  623. * delay and try again later or
  624. * reset driver.
  625. */
  626. goto map_error_handling1;
  627. }
  628. dma_handle2 = dma_map_single(dev, addr, size, direction);
  629. if (dma_mapping_error(dev, dma_handle2)) {
  630. /*
  631. * reduce current DMA mapping usage,
  632. * delay and try again later or
  633. * reset driver.
  634. */
  635. goto map_error_handling2;
  636. }
  637. ...
  638. map_error_handling2:
  639. dma_unmap_single(dma_handle1);
  640. map_error_handling1:
  641. Example 2::
  642. /*
  643. * if buffers are allocated in a loop, unmap all mapped buffers when
  644. * mapping error is detected in the middle
  645. */
  646. dma_addr_t dma_addr;
  647. dma_addr_t array[DMA_BUFFERS];
  648. int save_index = 0;
  649. for (i = 0; i < DMA_BUFFERS; i++) {
  650. ...
  651. dma_addr = dma_map_single(dev, addr, size, direction);
  652. if (dma_mapping_error(dev, dma_addr)) {
  653. /*
  654. * reduce current DMA mapping usage,
  655. * delay and try again later or
  656. * reset driver.
  657. */
  658. goto map_error_handling;
  659. }
  660. array[i].dma_addr = dma_addr;
  661. save_index++;
  662. }
  663. ...
  664. map_error_handling:
  665. for (i = 0; i < save_index; i++) {
  666. ...
  667. dma_unmap_single(array[i].dma_addr);
  668. }
  669. Networking drivers must call dev_kfree_skb() to free the socket buffer
  670. and return NETDEV_TX_OK if the DMA mapping fails on the transmit hook
  671. (ndo_start_xmit). This means that the socket buffer is just dropped in
  672. the failure case.
  673. SCSI drivers must return SCSI_MLQUEUE_HOST_BUSY if the DMA mapping
  674. fails in the queuecommand hook. This means that the SCSI subsystem
  675. passes the command to the driver again later.
  676. Optimizing Unmap State Space Consumption
  677. ========================================
  678. On many platforms, dma_unmap_{single,page}() is simply a nop.
  679. Therefore, keeping track of the mapping address and length is a waste
  680. of space. Instead of filling your drivers up with ifdefs and the like
  681. to "work around" this (which would defeat the whole purpose of a
  682. portable API) the following facilities are provided.
  683. Actually, instead of describing the macros one by one, we'll
  684. transform some example code.
  685. 1) Use DEFINE_DMA_UNMAP_{ADDR,LEN} in state saving structures.
  686. Example, before::
  687. struct ring_state {
  688. struct sk_buff *skb;
  689. dma_addr_t mapping;
  690. __u32 len;
  691. };
  692. after::
  693. struct ring_state {
  694. struct sk_buff *skb;
  695. DEFINE_DMA_UNMAP_ADDR(mapping);
  696. DEFINE_DMA_UNMAP_LEN(len);
  697. };
  698. 2) Use dma_unmap_{addr,len}_set() to set these values.
  699. Example, before::
  700. ringp->mapping = FOO;
  701. ringp->len = BAR;
  702. after::
  703. dma_unmap_addr_set(ringp, mapping, FOO);
  704. dma_unmap_len_set(ringp, len, BAR);
  705. 3) Use dma_unmap_{addr,len}() to access these values.
  706. Example, before::
  707. dma_unmap_single(dev, ringp->mapping, ringp->len,
  708. DMA_FROM_DEVICE);
  709. after::
  710. dma_unmap_single(dev,
  711. dma_unmap_addr(ringp, mapping),
  712. dma_unmap_len(ringp, len),
  713. DMA_FROM_DEVICE);
  714. It really should be self-explanatory. We treat the ADDR and LEN
  715. separately, because it is possible for an implementation to only
  716. need the address in order to perform the unmap operation.
  717. Platform Issues
  718. ===============
  719. If you are just writing drivers for Linux and do not maintain
  720. an architecture port for the kernel, you can safely skip down
  721. to "Closing".
  722. 1) Struct scatterlist requirements.
  723. You need to enable CONFIG_NEED_SG_DMA_LENGTH if the architecture
  724. supports IOMMUs (including software IOMMU).
  725. 2) ARCH_DMA_MINALIGN
  726. Architectures must ensure that kmalloc'ed buffer is
  727. DMA-safe. Drivers and subsystems depend on it. If an architecture
  728. isn't fully DMA-coherent (i.e. hardware doesn't ensure that data in
  729. the CPU cache is identical to data in main memory),
  730. ARCH_DMA_MINALIGN must be set so that the memory allocator
  731. makes sure that kmalloc'ed buffer doesn't share a cache line with
  732. the others. See arch/arm/include/asm/cache.h as an example.
  733. Note that ARCH_DMA_MINALIGN is about DMA memory alignment
  734. constraints. You don't need to worry about the architecture data
  735. alignment constraints (e.g. the alignment constraints about 64-bit
  736. objects).
  737. Closing
  738. =======
  739. This document, and the API itself, would not be in its current
  740. form without the feedback and suggestions from numerous individuals.
  741. We would like to specifically mention, in no particular order, the
  742. following people::
  743. Russell King <rmk@arm.linux.org.uk>
  744. Leo Dagum <dagum@barrel.engr.sgi.com>
  745. Ralf Baechle <ralf@oss.sgi.com>
  746. Grant Grundler <grundler@cup.hp.com>
  747. Jay Estabrook <Jay.Estabrook@compaq.com>
  748. Thomas Sailer <sailer@ife.ee.ethz.ch>
  749. Andrea Arcangeli <andrea@suse.de>
  750. Jens Axboe <jens.axboe@oracle.com>
  751. David Mosberger-Tang <davidm@hpl.hp.com>