DMA-mapping.txt 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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. Finally, if your device can only drive the low 24-bits of
  153. address during PCI bus mastering you might do something like:
  154. if (pci_set_dma_mask(pdev, DMA_24BIT_MASK)) {
  155. printk(KERN_WARNING
  156. "mydev: 24-bit DMA addressing not available.\n");
  157. goto ignore_this_device;
  158. }
  159. When pci_set_dma_mask() is successful, and returns zero, the PCI layer
  160. saves away this mask you have provided. The PCI layer will use this
  161. information later when you make DMA mappings.
  162. There is a case which we are aware of at this time, which is worth
  163. mentioning in this documentation. If your device supports multiple
  164. functions (for example a sound card provides playback and record
  165. functions) and the various different functions have _different_
  166. DMA addressing limitations, you may wish to probe each mask and
  167. only provide the functionality which the machine can handle. It
  168. is important that the last call to pci_set_dma_mask() be for the
  169. most specific mask.
  170. Here is pseudo-code showing how this might be done:
  171. #define PLAYBACK_ADDRESS_BITS DMA_32BIT_MASK
  172. #define RECORD_ADDRESS_BITS 0x00ffffff
  173. struct my_sound_card *card;
  174. struct pci_dev *pdev;
  175. ...
  176. if (!pci_set_dma_mask(pdev, PLAYBACK_ADDRESS_BITS)) {
  177. card->playback_enabled = 1;
  178. } else {
  179. card->playback_enabled = 0;
  180. printk(KERN_WARN "%s: Playback disabled due to DMA limitations.\n",
  181. card->name);
  182. }
  183. if (!pci_set_dma_mask(pdev, RECORD_ADDRESS_BITS)) {
  184. card->record_enabled = 1;
  185. } else {
  186. card->record_enabled = 0;
  187. printk(KERN_WARN "%s: Record disabled due to DMA limitations.\n",
  188. card->name);
  189. }
  190. A sound card was used as an example here because this genre of PCI
  191. devices seems to be littered with ISA chips given a PCI front end,
  192. and thus retaining the 16MB DMA addressing limitations of ISA.
  193. Types of DMA mappings
  194. There are two types of DMA mappings:
  195. - Consistent DMA mappings which are usually mapped at driver
  196. initialization, unmapped at the end and for which the hardware should
  197. guarantee that the device and the CPU can access the data
  198. in parallel and will see updates made by each other without any
  199. explicit software flushing.
  200. Think of "consistent" as "synchronous" or "coherent".
  201. The current default is to return consistent memory in the low 32
  202. bits of the PCI bus space. However, for future compatibility you
  203. should set the consistent mask even if this default is fine for your
  204. driver.
  205. Good examples of what to use consistent mappings for are:
  206. - Network card DMA ring descriptors.
  207. - SCSI adapter mailbox command data structures.
  208. - Device firmware microcode executed out of
  209. main memory.
  210. The invariant these examples all require is that any CPU store
  211. to memory is immediately visible to the device, and vice
  212. versa. Consistent mappings guarantee this.
  213. IMPORTANT: Consistent DMA memory does not preclude the usage of
  214. proper memory barriers. The CPU may reorder stores to
  215. consistent memory just as it may normal memory. Example:
  216. if it is important for the device to see the first word
  217. of a descriptor updated before the second, you must do
  218. something like:
  219. desc->word0 = address;
  220. wmb();
  221. desc->word1 = DESC_VALID;
  222. in order to get correct behavior on all platforms.
  223. Also, on some platforms your driver may need to flush CPU write
  224. buffers in much the same way as it needs to flush write buffers
  225. found in PCI bridges (such as by reading a register's value
  226. after writing it).
  227. - Streaming DMA mappings which are usually mapped for one DMA transfer,
  228. unmapped right after it (unless you use pci_dma_sync_* below) and for which
  229. hardware can optimize for sequential accesses.
  230. This of "streaming" as "asynchronous" or "outside the coherency
  231. domain".
  232. Good examples of what to use streaming mappings for are:
  233. - Networking buffers transmitted/received by a device.
  234. - Filesystem buffers written/read by a SCSI device.
  235. The interfaces for using this type of mapping were designed in
  236. such a way that an implementation can make whatever performance
  237. optimizations the hardware allows. To this end, when using
  238. such mappings you must be explicit about what you want to happen.
  239. Neither type of DMA mapping has alignment restrictions that come
  240. from PCI, although some devices may have such restrictions.
  241. Also, systems with caches that aren't DMA-coherent will work better
  242. when the underlying buffers don't share cache lines with other data.
  243. Using Consistent DMA mappings.
  244. To allocate and map large (PAGE_SIZE or so) consistent DMA regions,
  245. you should do:
  246. dma_addr_t dma_handle;
  247. cpu_addr = pci_alloc_consistent(pdev, size, &dma_handle);
  248. where pdev is a struct pci_dev *. This may be called in interrupt context.
  249. You should use dma_alloc_coherent (see DMA-API.txt) for buses
  250. where devices don't have struct pci_dev (like ISA, EISA).
  251. This argument is needed because the DMA translations may be bus
  252. specific (and often is private to the bus which the device is attached
  253. to).
  254. Size is the length of the region you want to allocate, in bytes.
  255. This routine will allocate RAM for that region, so it acts similarly to
  256. __get_free_pages (but takes size instead of a page order). If your
  257. driver needs regions sized smaller than a page, you may prefer using
  258. the pci_pool interface, described below.
  259. The consistent DMA mapping interfaces, for non-NULL pdev, will by
  260. default return a DMA address which is SAC (Single Address Cycle)
  261. addressable. Even if the device indicates (via PCI dma mask) that it
  262. may address the upper 32-bits and thus perform DAC cycles, consistent
  263. allocation will only return > 32-bit PCI addresses for DMA if the
  264. consistent dma mask has been explicitly changed via
  265. pci_set_consistent_dma_mask(). This is true of the pci_pool interface
  266. as well.
  267. pci_alloc_consistent returns two values: the virtual address which you
  268. can use to access it from the CPU and dma_handle which you pass to the
  269. card.
  270. The cpu return address and the DMA bus master address are both
  271. guaranteed to be aligned to the smallest PAGE_SIZE order which
  272. is greater than or equal to the requested size. This invariant
  273. exists (for example) to guarantee that if you allocate a chunk
  274. which is smaller than or equal to 64 kilobytes, the extent of the
  275. buffer you receive will not cross a 64K boundary.
  276. To unmap and free such a DMA region, you call:
  277. pci_free_consistent(pdev, size, cpu_addr, dma_handle);
  278. where pdev, size are the same as in the above call and cpu_addr and
  279. dma_handle are the values pci_alloc_consistent returned to you.
  280. This function may not be called in interrupt context.
  281. If your driver needs lots of smaller memory regions, you can write
  282. custom code to subdivide pages returned by pci_alloc_consistent,
  283. or you can use the pci_pool API to do that. A pci_pool is like
  284. a kmem_cache, but it uses pci_alloc_consistent not __get_free_pages.
  285. Also, it understands common hardware constraints for alignment,
  286. like queue heads needing to be aligned on N byte boundaries.
  287. Create a pci_pool like this:
  288. struct pci_pool *pool;
  289. pool = pci_pool_create(name, pdev, size, align, alloc);
  290. The "name" is for diagnostics (like a kmem_cache name); pdev and size
  291. are as above. The device's hardware alignment requirement for this
  292. type of data is "align" (which is expressed in bytes, and must be a
  293. power of two). If your device has no boundary crossing restrictions,
  294. pass 0 for alloc; passing 4096 says memory allocated from this pool
  295. must not cross 4KByte boundaries (but at that time it may be better to
  296. go for pci_alloc_consistent directly instead).
  297. Allocate memory from a pci pool like this:
  298. cpu_addr = pci_pool_alloc(pool, flags, &dma_handle);
  299. flags are SLAB_KERNEL if blocking is permitted (not in_interrupt nor
  300. holding SMP locks), SLAB_ATOMIC otherwise. Like pci_alloc_consistent,
  301. this returns two values, cpu_addr and dma_handle.
  302. Free memory that was allocated from a pci_pool like this:
  303. pci_pool_free(pool, cpu_addr, dma_handle);
  304. where pool is what you passed to pci_pool_alloc, and cpu_addr and
  305. dma_handle are the values pci_pool_alloc returned. This function
  306. may be called in interrupt context.
  307. Destroy a pci_pool by calling:
  308. pci_pool_destroy(pool);
  309. Make sure you've called pci_pool_free for all memory allocated
  310. from a pool before you destroy the pool. This function may not
  311. be called in interrupt context.
  312. DMA Direction
  313. The interfaces described in subsequent portions of this document
  314. take a DMA direction argument, which is an integer and takes on
  315. one of the following values:
  316. PCI_DMA_BIDIRECTIONAL
  317. PCI_DMA_TODEVICE
  318. PCI_DMA_FROMDEVICE
  319. PCI_DMA_NONE
  320. One should provide the exact DMA direction if you know it.
  321. PCI_DMA_TODEVICE means "from main memory to the PCI device"
  322. PCI_DMA_FROMDEVICE means "from the PCI device to main memory"
  323. It is the direction in which the data moves during the DMA
  324. transfer.
  325. You are _strongly_ encouraged to specify this as precisely
  326. as you possibly can.
  327. If you absolutely cannot know the direction of the DMA transfer,
  328. specify PCI_DMA_BIDIRECTIONAL. It means that the DMA can go in
  329. either direction. The platform guarantees that you may legally
  330. specify this, and that it will work, but this may be at the
  331. cost of performance for example.
  332. The value PCI_DMA_NONE is to be used for debugging. One can
  333. hold this in a data structure before you come to know the
  334. precise direction, and this will help catch cases where your
  335. direction tracking logic has failed to set things up properly.
  336. Another advantage of specifying this value precisely (outside of
  337. potential platform-specific optimizations of such) is for debugging.
  338. Some platforms actually have a write permission boolean which DMA
  339. mappings can be marked with, much like page protections in the user
  340. program address space. Such platforms can and do report errors in the
  341. kernel logs when the PCI controller hardware detects violation of the
  342. permission setting.
  343. Only streaming mappings specify a direction, consistent mappings
  344. implicitly have a direction attribute setting of
  345. PCI_DMA_BIDIRECTIONAL.
  346. The SCSI subsystem tells you the direction to use in the
  347. 'sc_data_direction' member of the SCSI command your driver is
  348. working on.
  349. For Networking drivers, it's a rather simple affair. For transmit
  350. packets, map/unmap them with the PCI_DMA_TODEVICE direction
  351. specifier. For receive packets, just the opposite, map/unmap them
  352. with the PCI_DMA_FROMDEVICE direction specifier.
  353. Using Streaming DMA mappings
  354. The streaming DMA mapping routines can be called from interrupt
  355. context. There are two versions of each map/unmap, one which will
  356. map/unmap a single memory region, and one which will map/unmap a
  357. scatterlist.
  358. To map a single region, you do:
  359. struct pci_dev *pdev = mydev->pdev;
  360. dma_addr_t dma_handle;
  361. void *addr = buffer->ptr;
  362. size_t size = buffer->len;
  363. dma_handle = pci_map_single(pdev, addr, size, direction);
  364. and to unmap it:
  365. pci_unmap_single(pdev, dma_handle, size, direction);
  366. You should call pci_unmap_single when the DMA activity is finished, e.g.
  367. from the interrupt which told you that the DMA transfer is done.
  368. Using cpu pointers like this for single mappings has a disadvantage,
  369. you cannot reference HIGHMEM memory in this way. Thus, there is a
  370. map/unmap interface pair akin to pci_{map,unmap}_single. These
  371. interfaces deal with page/offset pairs instead of cpu pointers.
  372. Specifically:
  373. struct pci_dev *pdev = mydev->pdev;
  374. dma_addr_t dma_handle;
  375. struct page *page = buffer->page;
  376. unsigned long offset = buffer->offset;
  377. size_t size = buffer->len;
  378. dma_handle = pci_map_page(pdev, page, offset, size, direction);
  379. ...
  380. pci_unmap_page(pdev, dma_handle, size, direction);
  381. Here, "offset" means byte offset within the given page.
  382. With scatterlists, you map a region gathered from several regions by:
  383. int i, count = pci_map_sg(pdev, sglist, nents, direction);
  384. struct scatterlist *sg;
  385. for_each_sg(sglist, sg, count, i) {
  386. hw_address[i] = sg_dma_address(sg);
  387. hw_len[i] = sg_dma_len(sg);
  388. }
  389. where nents is the number of entries in the sglist.
  390. The implementation is free to merge several consecutive sglist entries
  391. into one (e.g. if DMA mapping is done with PAGE_SIZE granularity, any
  392. consecutive sglist entries can be merged into one provided the first one
  393. ends and the second one starts on a page boundary - in fact this is a huge
  394. advantage for cards which either cannot do scatter-gather or have very
  395. limited number of scatter-gather entries) and returns the actual number
  396. of sg entries it mapped them to. On failure 0 is returned.
  397. Then you should loop count times (note: this can be less than nents times)
  398. and use sg_dma_address() and sg_dma_len() macros where you previously
  399. accessed sg->address and sg->length as shown above.
  400. To unmap a scatterlist, just call:
  401. pci_unmap_sg(pdev, sglist, nents, direction);
  402. Again, make sure DMA activity has already finished.
  403. PLEASE NOTE: The 'nents' argument to the pci_unmap_sg call must be
  404. the _same_ one you passed into the pci_map_sg call,
  405. it should _NOT_ be the 'count' value _returned_ from the
  406. pci_map_sg call.
  407. Every pci_map_{single,sg} call should have its pci_unmap_{single,sg}
  408. counterpart, because the bus address space is a shared resource (although
  409. in some ports the mapping is per each BUS so less devices contend for the
  410. same bus address space) and you could render the machine unusable by eating
  411. all bus addresses.
  412. If you need to use the same streaming DMA region multiple times and touch
  413. the data in between the DMA transfers, the buffer needs to be synced
  414. properly in order for the cpu and device to see the most uptodate and
  415. correct copy of the DMA buffer.
  416. So, firstly, just map it with pci_map_{single,sg}, and after each DMA
  417. transfer call either:
  418. pci_dma_sync_single_for_cpu(pdev, dma_handle, size, direction);
  419. or:
  420. pci_dma_sync_sg_for_cpu(pdev, sglist, nents, direction);
  421. as appropriate.
  422. Then, if you wish to let the device get at the DMA area again,
  423. finish accessing the data with the cpu, and then before actually
  424. giving the buffer to the hardware call either:
  425. pci_dma_sync_single_for_device(pdev, dma_handle, size, direction);
  426. or:
  427. pci_dma_sync_sg_for_device(dev, sglist, nents, direction);
  428. as appropriate.
  429. After the last DMA transfer call one of the DMA unmap routines
  430. pci_unmap_{single,sg}. If you don't touch the data from the first pci_map_*
  431. call till pci_unmap_*, then you don't have to call the pci_dma_sync_*
  432. routines at all.
  433. Here is pseudo code which shows a situation in which you would need
  434. to use the pci_dma_sync_*() interfaces.
  435. my_card_setup_receive_buffer(struct my_card *cp, char *buffer, int len)
  436. {
  437. dma_addr_t mapping;
  438. mapping = pci_map_single(cp->pdev, buffer, len, PCI_DMA_FROMDEVICE);
  439. cp->rx_buf = buffer;
  440. cp->rx_len = len;
  441. cp->rx_dma = mapping;
  442. give_rx_buf_to_card(cp);
  443. }
  444. ...
  445. my_card_interrupt_handler(int irq, void *devid, struct pt_regs *regs)
  446. {
  447. struct my_card *cp = devid;
  448. ...
  449. if (read_card_status(cp) == RX_BUF_TRANSFERRED) {
  450. struct my_card_header *hp;
  451. /* Examine the header to see if we wish
  452. * to accept the data. But synchronize
  453. * the DMA transfer with the CPU first
  454. * so that we see updated contents.
  455. */
  456. pci_dma_sync_single_for_cpu(cp->pdev, cp->rx_dma,
  457. cp->rx_len,
  458. PCI_DMA_FROMDEVICE);
  459. /* Now it is safe to examine the buffer. */
  460. hp = (struct my_card_header *) cp->rx_buf;
  461. if (header_is_ok(hp)) {
  462. pci_unmap_single(cp->pdev, cp->rx_dma, cp->rx_len,
  463. PCI_DMA_FROMDEVICE);
  464. pass_to_upper_layers(cp->rx_buf);
  465. make_and_setup_new_rx_buf(cp);
  466. } else {
  467. /* Just sync the buffer and give it back
  468. * to the card.
  469. */
  470. pci_dma_sync_single_for_device(cp->pdev,
  471. cp->rx_dma,
  472. cp->rx_len,
  473. PCI_DMA_FROMDEVICE);
  474. give_rx_buf_to_card(cp);
  475. }
  476. }
  477. }
  478. Drivers converted fully to this interface should not use virt_to_bus any
  479. longer, nor should they use bus_to_virt. Some drivers have to be changed a
  480. little bit, because there is no longer an equivalent to bus_to_virt in the
  481. dynamic DMA mapping scheme - you have to always store the DMA addresses
  482. returned by the pci_alloc_consistent, pci_pool_alloc, and pci_map_single
  483. calls (pci_map_sg stores them in the scatterlist itself if the platform
  484. supports dynamic DMA mapping in hardware) in your driver structures and/or
  485. in the card registers.
  486. All PCI drivers should be using these interfaces with no exceptions.
  487. It is planned to completely remove virt_to_bus() and bus_to_virt() as
  488. they are entirely deprecated. Some ports already do not provide these
  489. as it is impossible to correctly support them.
  490. Optimizing Unmap State Space Consumption
  491. On many platforms, pci_unmap_{single,page}() is simply a nop.
  492. Therefore, keeping track of the mapping address and length is a waste
  493. of space. Instead of filling your drivers up with ifdefs and the like
  494. to "work around" this (which would defeat the whole purpose of a
  495. portable API) the following facilities are provided.
  496. Actually, instead of describing the macros one by one, we'll
  497. transform some example code.
  498. 1) Use DECLARE_PCI_UNMAP_{ADDR,LEN} in state saving structures.
  499. Example, before:
  500. struct ring_state {
  501. struct sk_buff *skb;
  502. dma_addr_t mapping;
  503. __u32 len;
  504. };
  505. after:
  506. struct ring_state {
  507. struct sk_buff *skb;
  508. DECLARE_PCI_UNMAP_ADDR(mapping)
  509. DECLARE_PCI_UNMAP_LEN(len)
  510. };
  511. NOTE: DO NOT put a semicolon at the end of the DECLARE_*()
  512. macro.
  513. 2) Use pci_unmap_{addr,len}_set to set these values.
  514. Example, before:
  515. ringp->mapping = FOO;
  516. ringp->len = BAR;
  517. after:
  518. pci_unmap_addr_set(ringp, mapping, FOO);
  519. pci_unmap_len_set(ringp, len, BAR);
  520. 3) Use pci_unmap_{addr,len} to access these values.
  521. Example, before:
  522. pci_unmap_single(pdev, ringp->mapping, ringp->len,
  523. PCI_DMA_FROMDEVICE);
  524. after:
  525. pci_unmap_single(pdev,
  526. pci_unmap_addr(ringp, mapping),
  527. pci_unmap_len(ringp, len),
  528. PCI_DMA_FROMDEVICE);
  529. It really should be self-explanatory. We treat the ADDR and LEN
  530. separately, because it is possible for an implementation to only
  531. need the address in order to perform the unmap operation.
  532. Platform Issues
  533. If you are just writing drivers for Linux and do not maintain
  534. an architecture port for the kernel, you can safely skip down
  535. to "Closing".
  536. 1) Struct scatterlist requirements.
  537. Struct scatterlist must contain, at a minimum, the following
  538. members:
  539. struct page *page;
  540. unsigned int offset;
  541. unsigned int length;
  542. The base address is specified by a "page+offset" pair.
  543. Previous versions of struct scatterlist contained a "void *address"
  544. field that was sometimes used instead of page+offset. As of Linux
  545. 2.5., page+offset is always used, and the "address" field has been
  546. deleted.
  547. 2) More to come...
  548. Handling Errors
  549. DMA address space is limited on some architectures and an allocation
  550. failure can be determined by:
  551. - checking if pci_alloc_consistent returns NULL or pci_map_sg returns 0
  552. - checking the returned dma_addr_t of pci_map_single and pci_map_page
  553. by using pci_dma_mapping_error():
  554. dma_addr_t dma_handle;
  555. dma_handle = pci_map_single(pdev, addr, size, direction);
  556. if (pci_dma_mapping_error(pdev, dma_handle)) {
  557. /*
  558. * reduce current DMA mapping usage,
  559. * delay and try again later or
  560. * reset driver.
  561. */
  562. }
  563. Closing
  564. This document, and the API itself, would not be in it's current
  565. form without the feedback and suggestions from numerous individuals.
  566. We would like to specifically mention, in no particular order, the
  567. following people:
  568. Russell King <rmk@arm.linux.org.uk>
  569. Leo Dagum <dagum@barrel.engr.sgi.com>
  570. Ralf Baechle <ralf@oss.sgi.com>
  571. Grant Grundler <grundler@cup.hp.com>
  572. Jay Estabrook <Jay.Estabrook@compaq.com>
  573. Thomas Sailer <sailer@ife.ee.ethz.ch>
  574. Andrea Arcangeli <andrea@suse.de>
  575. Jens Axboe <jens.axboe@oracle.com>
  576. David Mosberger-Tang <davidm@hpl.hp.com>