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