DMA-mapping.txt 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. Dynamic DMA mapping
  2. ===================
  3. David S. Miller <davem@redhat.com>
  4. Richard Henderson <rth@cygnus.com>
  5. Jakub Jelinek <jakub@redhat.com>
  6. This document describes the DMA mapping system in terms of the pci_
  7. API. For a similar API that works for generic devices, see
  8. DMA-API.txt.
  9. Most of the 64bit platforms have special hardware that translates bus
  10. addresses (DMA addresses) into physical addresses. This is similar to
  11. how page tables and/or a TLB translates virtual addresses to physical
  12. addresses on a CPU. This is needed so that e.g. PCI devices can
  13. access with a Single Address Cycle (32bit DMA address) any page in the
  14. 64bit physical address space. Previously in Linux those 64bit
  15. platforms had to set artificial limits on the maximum RAM size in the
  16. system, so that the virt_to_bus() static scheme works (the DMA address
  17. translation tables were simply filled on bootup to map each bus
  18. address to the physical page __pa(bus_to_virt())).
  19. So that Linux can use the dynamic DMA mapping, it needs some help from the
  20. drivers, namely it has to take into account that DMA addresses should be
  21. mapped only for the time they are actually used and unmapped after the DMA
  22. transfer.
  23. The following API will work of course even on platforms where no such
  24. hardware exists, see e.g. include/asm-i386/pci.h for how it is implemented on
  25. top of the virt_to_bus interface.
  26. First of all, you should make sure
  27. #include <linux/pci.h>
  28. is in your driver. This file will obtain for you the definition of the
  29. dma_addr_t (which can hold any valid DMA address for the platform)
  30. type which should be used everywhere you hold a DMA (bus) address
  31. returned from the DMA mapping functions.
  32. What memory is DMA'able?
  33. The first piece of information you must know is what kernel memory can
  34. be used with the DMA mapping facilities. There has been an unwritten
  35. set of rules regarding this, and this text is an attempt to finally
  36. write them down.
  37. If you acquired your memory via the page allocator
  38. (i.e. __get_free_page*()) or the generic memory allocators
  39. (i.e. kmalloc() or kmem_cache_alloc()) then you may DMA to/from
  40. that memory using the addresses returned from those routines.
  41. This means specifically that you may _not_ use the memory/addresses
  42. returned from vmalloc() for DMA. It is possible to DMA to the
  43. _underlying_ memory mapped into a vmalloc() area, but this requires
  44. walking page tables to get the physical addresses, and then
  45. translating each of those pages back to a kernel address using
  46. something like __va(). [ EDIT: Update this when we integrate
  47. Gerd Knorr's generic code which does this. ]
  48. This rule also means that you may use neither kernel image addresses
  49. (items in data/text/bss segments), nor module image addresses, nor
  50. stack addresses for DMA. These could all be mapped somewhere entirely
  51. different than the rest of physical memory. Even if those classes of
  52. memory could physically work with DMA, you'd need to ensure the I/O
  53. buffers were cacheline-aligned. Without that, you'd see cacheline
  54. sharing problems (data corruption) on CPUs with DMA-incoherent caches.
  55. (The CPU could write to one word, DMA would write to a different one
  56. in the same cache line, and one of them could be overwritten.)
  57. Also, this means that you cannot take the return of a kmap()
  58. call and DMA to/from that. This is similar to vmalloc().
  59. What about block I/O and networking buffers? The block I/O and
  60. networking subsystems make sure that the buffers they use are valid
  61. for you to DMA from/to.
  62. DMA addressing limitations
  63. Does your device have any DMA addressing limitations? For example, is
  64. your device only capable of driving the low order 24-bits of address
  65. on the PCI bus for SAC DMA transfers? If so, you need to inform the
  66. PCI layer of this fact.
  67. By default, the kernel assumes that your device can address the full
  68. 32-bits in a SAC cycle. For a 64-bit DAC capable device, this needs
  69. to be increased. And for a device with limitations, as discussed in
  70. the previous paragraph, it needs to be decreased.
  71. pci_alloc_consistent() by default will return 32-bit DMA addresses.
  72. PCI-X specification requires PCI-X devices to support 64-bit
  73. addressing (DAC) for all transactions. And at least one platform (SGI
  74. SN2) requires 64-bit consistent allocations to operate correctly when
  75. the IO bus is in PCI-X mode. Therefore, like with pci_set_dma_mask(),
  76. it's good practice to call pci_set_consistent_dma_mask() to set the
  77. appropriate mask even if your device only supports 32-bit DMA
  78. (default) and especially if it's a PCI-X device.
  79. For correct operation, you must interrogate the PCI layer in your
  80. device probe routine to see if the PCI controller on the machine can
  81. properly support the DMA addressing limitation your device has. It is
  82. good style to do this even if your device holds the default setting,
  83. because this shows that you did think about these issues wrt. your
  84. device.
  85. The query is performed via a call to pci_set_dma_mask():
  86. int pci_set_dma_mask(struct pci_dev *pdev, u64 device_mask);
  87. The query for consistent allocations is performed via a call to
  88. pci_set_consistent_dma_mask():
  89. int pci_set_consistent_dma_mask(struct pci_dev *pdev, u64 device_mask);
  90. Here, pdev is a pointer to the PCI device struct of your device, and
  91. device_mask is a bit mask describing which bits of a PCI address your
  92. device supports. It returns zero if your card can perform DMA
  93. properly on the machine given the address mask you provided.
  94. If it returns non-zero, your device cannot perform DMA properly on
  95. this platform, and attempting to do so will result in undefined
  96. behavior. You must either use a different mask, or not use DMA.
  97. This means that in the failure case, you have three options:
  98. 1) Use another DMA mask, if possible (see below).
  99. 2) Use some non-DMA mode for data transfer, if possible.
  100. 3) Ignore this device and do not initialize it.
  101. It is recommended that your driver print a kernel KERN_WARNING message
  102. when you end up performing either #2 or #3. In this manner, if a user
  103. of your driver reports that performance is bad or that the device is not
  104. even detected, you can ask them for the kernel messages to find out
  105. exactly why.
  106. The standard 32-bit addressing PCI device would do something like
  107. this:
  108. if (pci_set_dma_mask(pdev, DMA_32BIT_MASK)) {
  109. printk(KERN_WARNING
  110. "mydev: No suitable DMA available.\n");
  111. goto ignore_this_device;
  112. }
  113. Another common scenario is a 64-bit capable device. The approach
  114. here is to try for 64-bit DAC addressing, but back down to a
  115. 32-bit mask should that fail. The PCI platform code may fail the
  116. 64-bit mask not because the platform is not capable of 64-bit
  117. addressing. Rather, it may fail in this case simply because
  118. 32-bit SAC addressing is done more efficiently than DAC addressing.
  119. Sparc64 is one platform which behaves in this way.
  120. Here is how you would handle a 64-bit capable device which can drive
  121. all 64-bits when accessing streaming DMA:
  122. int using_dac;
  123. if (!pci_set_dma_mask(pdev, DMA_64BIT_MASK)) {
  124. using_dac = 1;
  125. } else if (!pci_set_dma_mask(pdev, DMA_32BIT_MASK)) {
  126. using_dac = 0;
  127. } else {
  128. printk(KERN_WARNING
  129. "mydev: No suitable DMA available.\n");
  130. goto ignore_this_device;
  131. }
  132. If a card is capable of using 64-bit consistent allocations as well,
  133. the case would look like this:
  134. int using_dac, consistent_using_dac;
  135. if (!pci_set_dma_mask(pdev, DMA_64BIT_MASK)) {
  136. using_dac = 1;
  137. consistent_using_dac = 1;
  138. pci_set_consistent_dma_mask(pdev, DMA_64BIT_MASK);
  139. } else if (!pci_set_dma_mask(pdev, DMA_32BIT_MASK)) {
  140. using_dac = 0;
  141. consistent_using_dac = 0;
  142. pci_set_consistent_dma_mask(pdev, DMA_32BIT_MASK);
  143. } else {
  144. printk(KERN_WARNING
  145. "mydev: No suitable DMA available.\n");
  146. goto ignore_this_device;
  147. }
  148. pci_set_consistent_dma_mask() will always be able to set the same or a
  149. smaller mask as pci_set_dma_mask(). However for the rare case that a
  150. device driver only uses consistent allocations, one would have to
  151. check the return value from pci_set_consistent_dma_mask().
  152. If your 64-bit device is going to be an enormous consumer of DMA
  153. mappings, this can be problematic since the DMA mappings are a
  154. finite resource on many platforms. Please see the "DAC Addressing
  155. for Address Space Hungry Devices" section near the end of this
  156. document for how to handle this case.
  157. Finally, if your device can only drive the low 24-bits of
  158. address during PCI bus mastering you might do something like:
  159. if (pci_set_dma_mask(pdev, DMA_24BIT_MASK)) {
  160. printk(KERN_WARNING
  161. "mydev: 24-bit DMA addressing not available.\n");
  162. goto ignore_this_device;
  163. }
  164. [Better use DMA_24BIT_MASK instead of 0x00ffffff.
  165. See linux/include/dma-mapping.h for reference.]
  166. When pci_set_dma_mask() is successful, and returns zero, the PCI layer
  167. saves away this mask you have provided. The PCI layer will use this
  168. information later when you make DMA mappings.
  169. There is a case which we are aware of at this time, which is worth
  170. mentioning in this documentation. If your device supports multiple
  171. functions (for example a sound card provides playback and record
  172. functions) and the various different functions have _different_
  173. DMA addressing limitations, you may wish to probe each mask and
  174. only provide the functionality which the machine can handle. It
  175. is important that the last call to pci_set_dma_mask() be for the
  176. most specific mask.
  177. Here is pseudo-code showing how this might be done:
  178. #define PLAYBACK_ADDRESS_BITS DMA_32BIT_MASK
  179. #define RECORD_ADDRESS_BITS 0x00ffffff
  180. struct my_sound_card *card;
  181. struct pci_dev *pdev;
  182. ...
  183. if (!pci_set_dma_mask(pdev, PLAYBACK_ADDRESS_BITS)) {
  184. card->playback_enabled = 1;
  185. } else {
  186. card->playback_enabled = 0;
  187. printk(KERN_WARN "%s: Playback disabled due to DMA limitations.\n",
  188. card->name);
  189. }
  190. if (!pci_set_dma_mask(pdev, RECORD_ADDRESS_BITS)) {
  191. card->record_enabled = 1;
  192. } else {
  193. card->record_enabled = 0;
  194. printk(KERN_WARN "%s: Record disabled due to DMA limitations.\n",
  195. card->name);
  196. }
  197. A sound card was used as an example here because this genre of PCI
  198. devices seems to be littered with ISA chips given a PCI front end,
  199. and thus retaining the 16MB DMA addressing limitations of ISA.
  200. Types of DMA mappings
  201. There are two types of DMA mappings:
  202. - Consistent DMA mappings which are usually mapped at driver
  203. initialization, unmapped at the end and for which the hardware should
  204. guarantee that the device and the CPU can access the data
  205. in parallel and will see updates made by each other without any
  206. explicit software flushing.
  207. Think of "consistent" as "synchronous" or "coherent".
  208. The current default is to return consistent memory in the low 32
  209. bits of the PCI bus space. However, for future compatibility you
  210. should set the consistent mask even if this default is fine for your
  211. driver.
  212. Good examples of what to use consistent mappings for are:
  213. - Network card DMA ring descriptors.
  214. - SCSI adapter mailbox command data structures.
  215. - Device firmware microcode executed out of
  216. main memory.
  217. The invariant these examples all require is that any CPU store
  218. to memory is immediately visible to the device, and vice
  219. versa. Consistent mappings guarantee this.
  220. IMPORTANT: Consistent DMA memory does not preclude the usage of
  221. proper memory barriers. The CPU may reorder stores to
  222. consistent memory just as it may normal memory. Example:
  223. if it is important for the device to see the first word
  224. of a descriptor updated before the second, you must do
  225. something like:
  226. desc->word0 = address;
  227. wmb();
  228. desc->word1 = DESC_VALID;
  229. in order to get correct behavior on all platforms.
  230. Also, on some platforms your driver may need to flush CPU write
  231. buffers in much the same way as it needs to flush write buffers
  232. found in PCI bridges (such as by reading a register's value
  233. after writing it).
  234. - Streaming DMA mappings which are usually mapped for one DMA transfer,
  235. unmapped right after it (unless you use pci_dma_sync_* below) and for which
  236. hardware can optimize for sequential accesses.
  237. This of "streaming" as "asynchronous" or "outside the coherency
  238. domain".
  239. Good examples of what to use streaming mappings for are:
  240. - Networking buffers transmitted/received by a device.
  241. - Filesystem buffers written/read by a SCSI device.
  242. The interfaces for using this type of mapping were designed in
  243. such a way that an implementation can make whatever performance
  244. optimizations the hardware allows. To this end, when using
  245. such mappings you must be explicit about what you want to happen.
  246. Neither type of DMA mapping has alignment restrictions that come
  247. from PCI, although some devices may have such restrictions.
  248. Also, systems with caches that aren't DMA-coherent will work better
  249. when the underlying buffers don't share cache lines with other data.
  250. Using Consistent DMA mappings.
  251. To allocate and map large (PAGE_SIZE or so) consistent DMA regions,
  252. you should do:
  253. dma_addr_t dma_handle;
  254. cpu_addr = pci_alloc_consistent(dev, size, &dma_handle);
  255. where dev is a struct pci_dev *. You should pass NULL for PCI like buses
  256. where devices don't have struct pci_dev (like ISA, EISA). This may be
  257. called in interrupt context.
  258. This argument is needed because the DMA translations may be bus
  259. specific (and often is private to the bus which the device is attached
  260. to).
  261. Size is the length of the region you want to allocate, in bytes.
  262. This routine will allocate RAM for that region, so it acts similarly to
  263. __get_free_pages (but takes size instead of a page order). If your
  264. driver needs regions sized smaller than a page, you may prefer using
  265. the pci_pool interface, described below.
  266. The consistent DMA mapping interfaces, for non-NULL dev, will by
  267. default return a DMA address which is SAC (Single Address Cycle)
  268. addressable. Even if the device indicates (via PCI dma mask) that it
  269. may address the upper 32-bits and thus perform DAC cycles, consistent
  270. allocation will only return > 32-bit PCI addresses for DMA if the
  271. consistent dma mask has been explicitly changed via
  272. pci_set_consistent_dma_mask(). This is true of the pci_pool interface
  273. as well.
  274. pci_alloc_consistent returns two values: the virtual address which you
  275. can use to access it from the CPU and dma_handle which you pass to the
  276. card.
  277. The cpu return address and the DMA bus master address are both
  278. guaranteed to be aligned to the smallest PAGE_SIZE order which
  279. is greater than or equal to the requested size. This invariant
  280. exists (for example) to guarantee that if you allocate a chunk
  281. which is smaller than or equal to 64 kilobytes, the extent of the
  282. buffer you receive will not cross a 64K boundary.
  283. To unmap and free such a DMA region, you call:
  284. pci_free_consistent(dev, size, cpu_addr, dma_handle);
  285. where dev, size are the same as in the above call and cpu_addr and
  286. dma_handle are the values pci_alloc_consistent returned to you.
  287. This function may not be called in interrupt context.
  288. If your driver needs lots of smaller memory regions, you can write
  289. custom code to subdivide pages returned by pci_alloc_consistent,
  290. or you can use the pci_pool API to do that. A pci_pool is like
  291. a kmem_cache, but it uses pci_alloc_consistent not __get_free_pages.
  292. Also, it understands common hardware constraints for alignment,
  293. like queue heads needing to be aligned on N byte boundaries.
  294. Create a pci_pool like this:
  295. struct pci_pool *pool;
  296. pool = pci_pool_create(name, dev, size, align, alloc);
  297. The "name" is for diagnostics (like a kmem_cache name); dev and size
  298. are as above. The device's hardware alignment requirement for this
  299. type of data is "align" (which is expressed in bytes, and must be a
  300. power of two). If your device has no boundary crossing restrictions,
  301. pass 0 for alloc; passing 4096 says memory allocated from this pool
  302. must not cross 4KByte boundaries (but at that time it may be better to
  303. go for pci_alloc_consistent directly instead).
  304. Allocate memory from a pci pool like this:
  305. cpu_addr = pci_pool_alloc(pool, flags, &dma_handle);
  306. flags are SLAB_KERNEL if blocking is permitted (not in_interrupt nor
  307. holding SMP locks), SLAB_ATOMIC otherwise. Like pci_alloc_consistent,
  308. this returns two values, cpu_addr and dma_handle.
  309. Free memory that was allocated from a pci_pool like this:
  310. pci_pool_free(pool, cpu_addr, dma_handle);
  311. where pool is what you passed to pci_pool_alloc, and cpu_addr and
  312. dma_handle are the values pci_pool_alloc returned. This function
  313. may be called in interrupt context.
  314. Destroy a pci_pool by calling:
  315. pci_pool_destroy(pool);
  316. Make sure you've called pci_pool_free for all memory allocated
  317. from a pool before you destroy the pool. This function may not
  318. be called in interrupt context.
  319. DMA Direction
  320. The interfaces described in subsequent portions of this document
  321. take a DMA direction argument, which is an integer and takes on
  322. one of the following values:
  323. PCI_DMA_BIDIRECTIONAL
  324. PCI_DMA_TODEVICE
  325. PCI_DMA_FROMDEVICE
  326. PCI_DMA_NONE
  327. One should provide the exact DMA direction if you know it.
  328. PCI_DMA_TODEVICE means "from main memory to the PCI device"
  329. PCI_DMA_FROMDEVICE means "from the PCI device to main memory"
  330. It is the direction in which the data moves during the DMA
  331. transfer.
  332. You are _strongly_ encouraged to specify this as precisely
  333. as you possibly can.
  334. If you absolutely cannot know the direction of the DMA transfer,
  335. specify PCI_DMA_BIDIRECTIONAL. It means that the DMA can go in
  336. either direction. The platform guarantees that you may legally
  337. specify this, and that it will work, but this may be at the
  338. cost of performance for example.
  339. The value PCI_DMA_NONE is to be used for debugging. One can
  340. hold this in a data structure before you come to know the
  341. precise direction, and this will help catch cases where your
  342. direction tracking logic has failed to set things up properly.
  343. Another advantage of specifying this value precisely (outside of
  344. potential platform-specific optimizations of such) is for debugging.
  345. Some platforms actually have a write permission boolean which DMA
  346. mappings can be marked with, much like page protections in the user
  347. program address space. Such platforms can and do report errors in the
  348. kernel logs when the PCI controller hardware detects violation of the
  349. permission setting.
  350. Only streaming mappings specify a direction, consistent mappings
  351. implicitly have a direction attribute setting of
  352. PCI_DMA_BIDIRECTIONAL.
  353. The SCSI subsystem tells you the direction to use in the
  354. 'sc_data_direction' member of the SCSI command your driver is
  355. working on.
  356. For Networking drivers, it's a rather simple affair. For transmit
  357. packets, map/unmap them with the PCI_DMA_TODEVICE direction
  358. specifier. For receive packets, just the opposite, map/unmap them
  359. with the PCI_DMA_FROMDEVICE direction specifier.
  360. Using Streaming DMA mappings
  361. The streaming DMA mapping routines can be called from interrupt
  362. context. There are two versions of each map/unmap, one which will
  363. map/unmap a single memory region, and one which will map/unmap a
  364. scatterlist.
  365. To map a single region, you do:
  366. struct pci_dev *pdev = mydev->pdev;
  367. dma_addr_t dma_handle;
  368. void *addr = buffer->ptr;
  369. size_t size = buffer->len;
  370. dma_handle = pci_map_single(dev, addr, size, direction);
  371. and to unmap it:
  372. pci_unmap_single(dev, dma_handle, size, direction);
  373. You should call pci_unmap_single when the DMA activity is finished, e.g.
  374. from the interrupt which told you that the DMA transfer is done.
  375. Using cpu pointers like this for single mappings has a disadvantage,
  376. you cannot reference HIGHMEM memory in this way. Thus, there is a
  377. map/unmap interface pair akin to pci_{map,unmap}_single. These
  378. interfaces deal with page/offset pairs instead of cpu pointers.
  379. Specifically:
  380. struct pci_dev *pdev = mydev->pdev;
  381. dma_addr_t dma_handle;
  382. struct page *page = buffer->page;
  383. unsigned long offset = buffer->offset;
  384. size_t size = buffer->len;
  385. dma_handle = pci_map_page(dev, page, offset, size, direction);
  386. ...
  387. pci_unmap_page(dev, dma_handle, size, direction);
  388. Here, "offset" means byte offset within the given page.
  389. With scatterlists, you map a region gathered from several regions by:
  390. int i, count = pci_map_sg(dev, sglist, nents, direction);
  391. struct scatterlist *sg;
  392. for (i = 0, sg = sglist; i < count; i++, sg++) {
  393. hw_address[i] = sg_dma_address(sg);
  394. hw_len[i] = sg_dma_len(sg);
  395. }
  396. where nents is the number of entries in the sglist.
  397. The implementation is free to merge several consecutive sglist entries
  398. into one (e.g. if DMA mapping is done with PAGE_SIZE granularity, any
  399. consecutive sglist entries can be merged into one provided the first one
  400. ends and the second one starts on a page boundary - in fact this is a huge
  401. advantage for cards which either cannot do scatter-gather or have very
  402. limited number of scatter-gather entries) and returns the actual number
  403. of sg entries it mapped them to. On failure 0 is returned.
  404. Then you should loop count times (note: this can be less than nents times)
  405. and use sg_dma_address() and sg_dma_len() macros where you previously
  406. accessed sg->address and sg->length as shown above.
  407. To unmap a scatterlist, just call:
  408. pci_unmap_sg(dev, sglist, nents, direction);
  409. Again, make sure DMA activity has already finished.
  410. PLEASE NOTE: The 'nents' argument to the pci_unmap_sg call must be
  411. the _same_ one you passed into the pci_map_sg call,
  412. it should _NOT_ be the 'count' value _returned_ from the
  413. pci_map_sg call.
  414. Every pci_map_{single,sg} call should have its pci_unmap_{single,sg}
  415. counterpart, because the bus address space is a shared resource (although
  416. in some ports the mapping is per each BUS so less devices contend for the
  417. same bus address space) and you could render the machine unusable by eating
  418. all bus addresses.
  419. If you need to use the same streaming DMA region multiple times and touch
  420. the data in between the DMA transfers, the buffer needs to be synced
  421. properly in order for the cpu and device to see the most uptodate and
  422. correct copy of the DMA buffer.
  423. So, firstly, just map it with pci_map_{single,sg}, and after each DMA
  424. transfer call either:
  425. pci_dma_sync_single_for_cpu(dev, dma_handle, size, direction);
  426. or:
  427. pci_dma_sync_sg_for_cpu(dev, sglist, nents, direction);
  428. as appropriate.
  429. Then, if you wish to let the device get at the DMA area again,
  430. finish accessing the data with the cpu, and then before actually
  431. giving the buffer to the hardware call either:
  432. pci_dma_sync_single_for_device(dev, dma_handle, size, direction);
  433. or:
  434. pci_dma_sync_sg_for_device(dev, sglist, nents, direction);
  435. as appropriate.
  436. After the last DMA transfer call one of the DMA unmap routines
  437. pci_unmap_{single,sg}. If you don't touch the data from the first pci_map_*
  438. call till pci_unmap_*, then you don't have to call the pci_dma_sync_*
  439. routines at all.
  440. Here is pseudo code which shows a situation in which you would need
  441. to use the pci_dma_sync_*() interfaces.
  442. my_card_setup_receive_buffer(struct my_card *cp, char *buffer, int len)
  443. {
  444. dma_addr_t mapping;
  445. mapping = pci_map_single(cp->pdev, buffer, len, PCI_DMA_FROMDEVICE);
  446. cp->rx_buf = buffer;
  447. cp->rx_len = len;
  448. cp->rx_dma = mapping;
  449. give_rx_buf_to_card(cp);
  450. }
  451. ...
  452. my_card_interrupt_handler(int irq, void *devid, struct pt_regs *regs)
  453. {
  454. struct my_card *cp = devid;
  455. ...
  456. if (read_card_status(cp) == RX_BUF_TRANSFERRED) {
  457. struct my_card_header *hp;
  458. /* Examine the header to see if we wish
  459. * to accept the data. But synchronize
  460. * the DMA transfer with the CPU first
  461. * so that we see updated contents.
  462. */
  463. pci_dma_sync_single_for_cpu(cp->pdev, cp->rx_dma,
  464. cp->rx_len,
  465. PCI_DMA_FROMDEVICE);
  466. /* Now it is safe to examine the buffer. */
  467. hp = (struct my_card_header *) cp->rx_buf;
  468. if (header_is_ok(hp)) {
  469. pci_unmap_single(cp->pdev, cp->rx_dma, cp->rx_len,
  470. PCI_DMA_FROMDEVICE);
  471. pass_to_upper_layers(cp->rx_buf);
  472. make_and_setup_new_rx_buf(cp);
  473. } else {
  474. /* Just sync the buffer and give it back
  475. * to the card.
  476. */
  477. pci_dma_sync_single_for_device(cp->pdev,
  478. cp->rx_dma,
  479. cp->rx_len,
  480. PCI_DMA_FROMDEVICE);
  481. give_rx_buf_to_card(cp);
  482. }
  483. }
  484. }
  485. Drivers converted fully to this interface should not use virt_to_bus any
  486. longer, nor should they use bus_to_virt. Some drivers have to be changed a
  487. little bit, because there is no longer an equivalent to bus_to_virt in the
  488. dynamic DMA mapping scheme - you have to always store the DMA addresses
  489. returned by the pci_alloc_consistent, pci_pool_alloc, and pci_map_single
  490. calls (pci_map_sg stores them in the scatterlist itself if the platform
  491. supports dynamic DMA mapping in hardware) in your driver structures and/or
  492. in the card registers.
  493. All PCI drivers should be using these interfaces with no exceptions.
  494. It is planned to completely remove virt_to_bus() and bus_to_virt() as
  495. they are entirely deprecated. Some ports already do not provide these
  496. as it is impossible to correctly support them.
  497. 64-bit DMA and DAC cycle support
  498. Do you understand all of the text above? Great, then you already
  499. know how to use 64-bit DMA addressing under Linux. Simply make
  500. the appropriate pci_set_dma_mask() calls based upon your cards
  501. capabilities, then use the mapping APIs above.
  502. It is that simple.
  503. Well, not for some odd devices. See the next section for information
  504. about that.
  505. DAC Addressing for Address Space Hungry Devices
  506. There exists a class of devices which do not mesh well with the PCI
  507. DMA mapping API. By definition these "mappings" are a finite
  508. resource. The number of total available mappings per bus is platform
  509. specific, but there will always be a reasonable amount.
  510. What is "reasonable"? Reasonable means that networking and block I/O
  511. devices need not worry about using too many mappings.
  512. As an example of a problematic device, consider compute cluster cards.
  513. They can potentially need to access gigabytes of memory at once via
  514. DMA. Dynamic mappings are unsuitable for this kind of access pattern.
  515. To this end we've provided a small API by which a device driver
  516. may use DAC cycles to directly address all of physical memory.
  517. Not all platforms support this, but most do. It is easy to determine
  518. whether the platform will work properly at probe time.
  519. First, understand that there may be a SEVERE performance penalty for
  520. using these interfaces on some platforms. Therefore, you MUST only
  521. use these interfaces if it is absolutely required. %99 of devices can
  522. use the normal APIs without any problems.
  523. Note that for streaming type mappings you must either use these
  524. interfaces, or the dynamic mapping interfaces above. You may not mix
  525. usage of both for the same device. Such an act is illegal and is
  526. guaranteed to put a banana in your tailpipe.
  527. However, consistent mappings may in fact be used in conjunction with
  528. these interfaces. Remember that, as defined, consistent mappings are
  529. always going to be SAC addressable.
  530. The first thing your driver needs to do is query the PCI platform
  531. layer if it is capable of handling your devices DAC addressing
  532. capabilities:
  533. int pci_dac_dma_supported(struct pci_dev *hwdev, u64 mask);
  534. You may not use the following interfaces if this routine fails.
  535. Next, DMA addresses using this API are kept track of using the
  536. dma64_addr_t type. It is guaranteed to be big enough to hold any
  537. DAC address the platform layer will give to you from the following
  538. routines. If you have consistent mappings as well, you still
  539. use plain dma_addr_t to keep track of those.
  540. All mappings obtained here will be direct. The mappings are not
  541. translated, and this is the purpose of this dialect of the DMA API.
  542. All routines work with page/offset pairs. This is the _ONLY_ way to
  543. portably refer to any piece of memory. If you have a cpu pointer
  544. (which may be validly DMA'd too) you may easily obtain the page
  545. and offset using something like this:
  546. struct page *page = virt_to_page(ptr);
  547. unsigned long offset = offset_in_page(ptr);
  548. Here are the interfaces:
  549. dma64_addr_t pci_dac_page_to_dma(struct pci_dev *pdev,
  550. struct page *page,
  551. unsigned long offset,
  552. int direction);
  553. The DAC address for the tuple PAGE/OFFSET are returned. The direction
  554. argument is the same as for pci_{map,unmap}_single(). The same rules
  555. for cpu/device access apply here as for the streaming mapping
  556. interfaces. To reiterate:
  557. The cpu may touch the buffer before pci_dac_page_to_dma.
  558. The device may touch the buffer after pci_dac_page_to_dma
  559. is made, but the cpu may NOT.
  560. When the DMA transfer is complete, invoke:
  561. void pci_dac_dma_sync_single_for_cpu(struct pci_dev *pdev,
  562. dma64_addr_t dma_addr,
  563. size_t len, int direction);
  564. This must be done before the CPU looks at the buffer again.
  565. This interface behaves identically to pci_dma_sync_{single,sg}_for_cpu().
  566. And likewise, if you wish to let the device get back at the buffer after
  567. the cpu has read/written it, invoke:
  568. void pci_dac_dma_sync_single_for_device(struct pci_dev *pdev,
  569. dma64_addr_t dma_addr,
  570. size_t len, int direction);
  571. before letting the device access the DMA area again.
  572. If you need to get back to the PAGE/OFFSET tuple from a dma64_addr_t
  573. the following interfaces are provided:
  574. struct page *pci_dac_dma_to_page(struct pci_dev *pdev,
  575. dma64_addr_t dma_addr);
  576. unsigned long pci_dac_dma_to_offset(struct pci_dev *pdev,
  577. dma64_addr_t dma_addr);
  578. This is possible with the DAC interfaces purely because they are
  579. not translated in any way.
  580. Optimizing Unmap State Space Consumption
  581. On many platforms, pci_unmap_{single,page}() is simply a nop.
  582. Therefore, keeping track of the mapping address and length is a waste
  583. of space. Instead of filling your drivers up with ifdefs and the like
  584. to "work around" this (which would defeat the whole purpose of a
  585. portable API) the following facilities are provided.
  586. Actually, instead of describing the macros one by one, we'll
  587. transform some example code.
  588. 1) Use DECLARE_PCI_UNMAP_{ADDR,LEN} in state saving structures.
  589. Example, before:
  590. struct ring_state {
  591. struct sk_buff *skb;
  592. dma_addr_t mapping;
  593. __u32 len;
  594. };
  595. after:
  596. struct ring_state {
  597. struct sk_buff *skb;
  598. DECLARE_PCI_UNMAP_ADDR(mapping)
  599. DECLARE_PCI_UNMAP_LEN(len)
  600. };
  601. NOTE: DO NOT put a semicolon at the end of the DECLARE_*()
  602. macro.
  603. 2) Use pci_unmap_{addr,len}_set to set these values.
  604. Example, before:
  605. ringp->mapping = FOO;
  606. ringp->len = BAR;
  607. after:
  608. pci_unmap_addr_set(ringp, mapping, FOO);
  609. pci_unmap_len_set(ringp, len, BAR);
  610. 3) Use pci_unmap_{addr,len} to access these values.
  611. Example, before:
  612. pci_unmap_single(pdev, ringp->mapping, ringp->len,
  613. PCI_DMA_FROMDEVICE);
  614. after:
  615. pci_unmap_single(pdev,
  616. pci_unmap_addr(ringp, mapping),
  617. pci_unmap_len(ringp, len),
  618. PCI_DMA_FROMDEVICE);
  619. It really should be self-explanatory. We treat the ADDR and LEN
  620. separately, because it is possible for an implementation to only
  621. need the address in order to perform the unmap operation.
  622. Platform Issues
  623. If you are just writing drivers for Linux and do not maintain
  624. an architecture port for the kernel, you can safely skip down
  625. to "Closing".
  626. 1) Struct scatterlist requirements.
  627. Struct scatterlist must contain, at a minimum, the following
  628. members:
  629. struct page *page;
  630. unsigned int offset;
  631. unsigned int length;
  632. The base address is specified by a "page+offset" pair.
  633. Previous versions of struct scatterlist contained a "void *address"
  634. field that was sometimes used instead of page+offset. As of Linux
  635. 2.5., page+offset is always used, and the "address" field has been
  636. deleted.
  637. 2) More to come...
  638. Handling Errors
  639. DMA address space is limited on some architectures and an allocation
  640. failure can be determined by:
  641. - checking if pci_alloc_consistent returns NULL or pci_map_sg returns 0
  642. - checking the returned dma_addr_t of pci_map_single and pci_map_page
  643. by using pci_dma_mapping_error():
  644. dma_addr_t dma_handle;
  645. dma_handle = pci_map_single(dev, addr, size, direction);
  646. if (pci_dma_mapping_error(dma_handle)) {
  647. /*
  648. * reduce current DMA mapping usage,
  649. * delay and try again later or
  650. * reset driver.
  651. */
  652. }
  653. Closing
  654. This document, and the API itself, would not be in it's current
  655. form without the feedback and suggestions from numerous individuals.
  656. We would like to specifically mention, in no particular order, the
  657. following people:
  658. Russell King <rmk@arm.linux.org.uk>
  659. Leo Dagum <dagum@barrel.engr.sgi.com>
  660. Ralf Baechle <ralf@oss.sgi.com>
  661. Grant Grundler <grundler@cup.hp.com>
  662. Jay Estabrook <Jay.Estabrook@compaq.com>
  663. Thomas Sailer <sailer@ife.ee.ethz.ch>
  664. Andrea Arcangeli <andrea@suse.de>
  665. Jens Axboe <axboe@suse.de>
  666. David Mosberger-Tang <davidm@hpl.hp.com>