← Documents Documentation/core-api/dma-api.rst GitHub 원문 ↗

Linux 6.18.37 · Core API

Dynamic DMA mapping using the generic device

Linux generic DMA API의 coherent, streaming, IOVA, non-coherent allocation과 DMA API debugging interface를 함수 계약 중심으로 설명합니다.

Source pathDocumentation/core-api/dma-api.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약과 해설

dma-api.rst:1-868

이 문서는 Linux generic device DMA API의 기준 명세입니다. Driver는 `dma_addr_t`를 CPU address처럼 직접 사용하지 않고, device DMA mask와 mapping size 한계를 설정한 뒤 각 allocate/map 함수의 반환값을 검사해야 합니다.

일반 driver는 Part I의 coherent, streaming, scatter/gather, attribute, IOVA API를 사용합니다. Non-coherent platform을 반드시 지원하는 경우에만 Part II의 explicit ownership API를 사용하며, cache line 경계와 CPU/device synchronization 규칙을 엄격히 지켜야 합니다.

Part III의 DMA API debugging은 잘못된 함수나 size로 unmap하는 오류, mapping error 검사 누락, mapping leak를 추적합니다. Production kernel에는 성능 비용 때문에 활성화하지 않으며 debugfs와 boot parameter로 출력 범위 및 entry 수를 조정합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 ============================================
2 Dynamic DMA mapping using the generic device
3 ============================================
4
5 :Author: James E.J. Bottomley <[email protected]>
6
7 This document describes the DMA API. For a more gentle introduction
8 of the API (and actual examples), see Documentation/core-api/dma-api-howto.rst.
9
10 This API is split into two pieces. Part I describes the basic API.
11 Part II describes extensions for supporting non-coherent memory
12 machines. Unless you know that your driver absolutely has to support
13 non-coherent platforms (this is usually only legacy platforms) you
14 should only use the API described in part I.
15
16 Part I - DMA API
17 ----------------
18
19 To get the DMA API, you must #include <linux/dma-mapping.h>. This
20 provides dma_addr_t and the interfaces described below.
21
22 A dma_addr_t can hold any valid DMA address for the platform. It can be
23 given to a device to use as a DMA source or target. A CPU cannot reference
24 a dma_addr_t directly because there may be translation between its physical
25 address space and the DMA address space.
26
27 Part Ia - Using large DMA-coherent buffers
28 ------------------------------------------
29
30 ::
31
32 void *
33 dma_alloc_coherent(struct device *dev, size_t size,
34 dma_addr_t *dma_handle, gfp_t flag)
35
36 Coherent memory is memory for which a write by either the device or
37 the processor can immediately be read by the processor or device
38 without having to worry about caching effects. (You may however need
39 to make sure to flush the processor's write buffers before telling
40 devices to read that memory.)
41
42 This routine allocates a region of <size> bytes of coherent memory.
43
44 It returns a pointer to the allocated region (in the processor's virtual
45 address space) or NULL if the allocation failed.
46
47 It also returns a <dma_handle> which may be cast to an unsigned integer the
48 same width as the bus and given to the device as the DMA address base of
49 the region.
50
51 Note: coherent memory can be expensive on some platforms, and the
52 minimum allocation length may be as big as a page, so you should
53 consolidate your requests for coherent memory as much as possible.
54 The simplest way to do that is to use the dma_pool calls (see below).
55
56 The flag parameter allows the caller to specify the ``GFP_`` flags (see
57 kmalloc()) for the allocation (the implementation may ignore flags that affect
58 the location of the returned memory, like GFP_DMA).
59
60 ::
61
62 void
63 dma_free_coherent(struct device *dev, size_t size, void *cpu_addr,
64 dma_addr_t dma_handle)
65
66 Free a previously allocated region of coherent memory. dev, size and dma_handle
67 must all be the same as those passed into dma_alloc_coherent(). cpu_addr must
68 be the virtual address returned by dma_alloc_coherent().
69
70 Note that unlike the sibling allocation call, this routine may only be called
71 with IRQs enabled.
72
73
74 Part Ib - Using small DMA-coherent buffers
75 ------------------------------------------
76
77 To get this part of the DMA API, you must #include <linux/dmapool.h>
78
79 Many drivers need lots of small DMA-coherent memory regions for DMA
80 descriptors or I/O buffers. Rather than allocating in units of a page
81 or more using dma_alloc_coherent(), you can use DMA pools. These work
82 much like a struct kmem_cache, except that they use the DMA-coherent allocator,
83 not __get_free_pages(). Also, they understand common hardware constraints
84 for alignment, like queue heads needing to be aligned on N-byte boundaries.
85
86 .. kernel-doc:: mm/dmapool.c
87 :export:
88
89 .. kernel-doc:: include/linux/dmapool.h
90
91
92 Part Ic - DMA addressing limitations
93 ------------------------------------
94
95 DMA mask is a bit mask of the addressable region for the device. In other words,
96 if applying the DMA mask (a bitwise AND operation) to the DMA address of a
97 memory region does not clear any bits in the address, then the device can
98 perform DMA to that memory region.
99
100 All the below functions which set a DMA mask may fail if the requested mask
101 cannot be used with the device, or if the device is not capable of doing DMA.
102
103 ::
104
105 int
106 dma_set_mask_and_coherent(struct device *dev, u64 mask)
107
108 Updates both streaming and coherent DMA masks.
109
110 Returns: 0 if successful and a negative error if not.
111
112 ::
113
114 int
115 dma_set_mask(struct device *dev, u64 mask)
116
117 Updates only the streaming DMA mask.
118
119 Returns: 0 if successful and a negative error if not.
120
121 ::
122
123 int
124 dma_set_coherent_mask(struct device *dev, u64 mask)
125
126 Updates only the coherent DMA mask.
127
128 Returns: 0 if successful and a negative error if not.
129
130 ::
131
132 u64
133 dma_get_required_mask(struct device *dev)
134
135 This API returns the mask that the platform requires to
136 operate efficiently. Usually this means the returned mask
137 is the minimum required to cover all of memory. Examining the
138 required mask gives drivers with variable descriptor sizes the
139 opportunity to use smaller descriptors as necessary.
140
141 Requesting the required mask does not alter the current mask. If you
142 wish to take advantage of it, you should issue a dma_set_mask()
143 call to set the mask to the value returned.
144
145 ::
146
147 size_t
148 dma_max_mapping_size(struct device *dev);
149
150 Returns the maximum size of a mapping for the device. The size parameter
151 of the mapping functions like dma_map_single(), dma_map_page() and
152 others should not be larger than the returned value.
153
154 ::
155
156 size_t
157 dma_opt_mapping_size(struct device *dev);
158
159 Returns the maximum optimal size of a mapping for the device.
160
161 Mapping larger buffers may take much longer in certain scenarios. In
162 addition, for high-rate short-lived streaming mappings, the upfront time
163 spent on the mapping may account for an appreciable part of the total
164 request lifetime. As such, if splitting larger requests incurs no
165 significant performance penalty, then device drivers are advised to
166 limit total DMA streaming mappings length to the returned value.
167
168 ::
169
170 bool
171 dma_need_sync(struct device *dev, dma_addr_t dma_addr);
172
173 Returns %true if dma_sync_single_for_{device,cpu} calls are required to
174 transfer memory ownership. Returns %false if those calls can be skipped.
175
176 ::
177
178 unsigned long
179 dma_get_merge_boundary(struct device *dev);
180
181 Returns the DMA merge boundary. If the device cannot merge any DMA address
182 segments, the function returns 0.
183
184 Part Id - Streaming DMA mappings
185 --------------------------------
186
187 Streaming DMA allows to map an existing buffer for DMA transfers and then
188 unmap it when finished. Map functions are not guaranteed to succeed, so the
189 return value must be checked.
190
191 .. note::
192
193 In particular, mapping may fail for memory not addressable by the
194 device, e.g. if it is not within the DMA mask of the device and/or a
195 connecting bus bridge. Streaming DMA functions try to overcome such
196 addressing constraints, either by using an IOMMU (a device which maps
197 I/O DMA addresses to physical memory addresses), or by copying the
198 data to/from a bounce buffer if the kernel is configured with a
199 :doc:`SWIOTLB <swiotlb>`. However, these methods are not always
200 available, and even if they are, they may still fail for a number of
201 reasons.
202
203 In short, a device driver may need to be wary of where buffers are
204 located in physical memory, especially if the DMA mask is less than 32
205 bits.
206
207 ::
208
209 dma_addr_t
210 dma_map_single(struct device *dev, void *cpu_addr, size_t size,
211 enum dma_data_direction direction)
212
213 Maps a piece of processor virtual memory so it can be accessed by the
214 device and returns the DMA address of the memory.
215
216 The DMA API uses a strongly typed enumerator for its direction:
217
218 ======================= =============================================
219 DMA_NONE no direction (used for debugging)
220 DMA_TO_DEVICE data is going from the memory to the device
221 DMA_FROM_DEVICE data is coming from the device to the memory
222 DMA_BIDIRECTIONAL direction isn't known
223 ======================= =============================================
224
225 .. note::
226
227 Contiguous kernel virtual space may not be contiguous as
228 physical memory. Since this API does not provide any scatter/gather
229 capability, it will fail if the user tries to map a non-physically
230 contiguous piece of memory. For this reason, memory to be mapped by
231 this API should be obtained from sources which guarantee it to be
232 physically contiguous (like kmalloc).
233
234 .. warning::
235
236 Memory coherency operates at a granularity called the cache
237 line width. In order for memory mapped by this API to operate
238 correctly, the mapped region must begin exactly on a cache line
239 boundary and end exactly on one (to prevent two separately mapped
240 regions from sharing a single cache line). Since the cache line size
241 may not be known at compile time, the API will not enforce this
242 requirement. Therefore, it is recommended that driver writers who
243 don't take special care to determine the cache line size at run time
244 only map virtual regions that begin and end on page boundaries (which
245 are guaranteed also to be cache line boundaries).
246
247 DMA_TO_DEVICE synchronisation must be done after the last modification
248 of the memory region by the software and before it is handed off to
249 the device. Once this primitive is used, memory covered by this
250 primitive should be treated as read-only by the device. If the device
251 may write to it at any point, it should be DMA_BIDIRECTIONAL (see
252 below).
253
254 DMA_FROM_DEVICE synchronisation must be done before the driver
255 accesses data that may be changed by the device. This memory should
256 be treated as read-only by the driver. If the driver needs to write
257 to it at any point, it should be DMA_BIDIRECTIONAL (see below).
258
259 DMA_BIDIRECTIONAL requires special handling: it means that the driver
260 isn't sure if the memory was modified before being handed off to the
261 device and also isn't sure if the device will also modify it. Thus,
262 you must always sync bidirectional memory twice: once before the
263 memory is handed off to the device (to make sure all memory changes
264 are flushed from the processor) and once before the data may be
265 accessed after being used by the device (to make sure any processor
266 cache lines are updated with data that the device may have changed).
267
268 ::
269
270 void
271 dma_unmap_single(struct device *dev, dma_addr_t dma_addr, size_t size,
272 enum dma_data_direction direction)
273
274 Unmaps the region previously mapped. All the parameters passed in
275 must be identical to those passed to (and returned by) dma_map_single().
276
277 ::
278
279 dma_addr_t
280 dma_map_page(struct device *dev, struct page *page,
281 unsigned long offset, size_t size,
282 enum dma_data_direction direction)
283
284 void
285 dma_unmap_page(struct device *dev, dma_addr_t dma_address, size_t size,
286 enum dma_data_direction direction)
287
288 API for mapping and unmapping for pages. All the notes and warnings
289 for the other mapping APIs apply here. Also, although the <offset>
290 and <size> parameters are provided to do partial page mapping, it is
291 recommended that you never use these unless you really know what the
292 cache width is.
293
294 ::
295
296 dma_addr_t
297 dma_map_resource(struct device *dev, phys_addr_t phys_addr, size_t size,
298 enum dma_data_direction dir, unsigned long attrs)
299
300 void
301 dma_unmap_resource(struct device *dev, dma_addr_t addr, size_t size,
302 enum dma_data_direction dir, unsigned long attrs)
303
304 API for mapping and unmapping for MMIO resources. All the notes and
305 warnings for the other mapping APIs apply here. The API should only be
306 used to map device MMIO resources, mapping of RAM is not permitted.
307
308 ::
309
310 int
311 dma_mapping_error(struct device *dev, dma_addr_t dma_addr)
312
313 In some circumstances dma_map_single(), dma_map_page() and dma_map_resource()
314 will fail to create a mapping. A driver can check for these errors by testing
315 the returned DMA address with dma_mapping_error(). A non-zero return value
316 means the mapping could not be created and the driver should take appropriate
317 action (e.g. reduce current DMA mapping usage or delay and try again later).
318
319 ::
320
321 int
322 dma_map_sg(struct device *dev, struct scatterlist *sg,
323 int nents, enum dma_data_direction direction)
324
325 Maps a scatter/gather list for DMA. Returns the number of DMA address segments
326 mapped, which may be smaller than <nents> passed in if several consecutive
327 sglist entries are merged (e.g. with an IOMMU, or if some adjacent segments
328 just happen to be physically contiguous).
329
330 Please note that the sg cannot be mapped again if it has been mapped once.
331 The mapping process is allowed to destroy information in the sg.
332
333 As with the other mapping interfaces, dma_map_sg() can fail. When it
334 does, 0 is returned and a driver must take appropriate action. It is
335 critical that the driver do something, in the case of a block driver
336 aborting the request or even oopsing is better than doing nothing and
337 corrupting the filesystem.
338
339 With scatterlists, you use the resulting mapping like this::
340
341 int i, count = dma_map_sg(dev, sglist, nents, direction);
342 struct scatterlist *sg;
343
344 for_each_sg(sglist, sg, count, i) {
345 hw_address[i] = sg_dma_address(sg);
346 hw_len[i] = sg_dma_len(sg);
347 }
348
349 where nents is the number of entries in the sglist.
350
351 The implementation is free to merge several consecutive sglist entries
352 into one. The returned number is the actual number of sg entries it
353 mapped them to. On failure, 0 is returned.
354
355 Then you should loop count times (note: this can be less than nents times)
356 and use sg_dma_address() and sg_dma_len() macros where you previously
357 accessed sg->address and sg->length as shown above.
358
359 ::
360
361 void
362 dma_unmap_sg(struct device *dev, struct scatterlist *sg,
363 int nents, enum dma_data_direction direction)
364
365 Unmap the previously mapped scatter/gather list. All the parameters
366 must be the same as those and passed in to the scatter/gather mapping
367 API.
368
369 Note: <nents> must be the number you passed in, *not* the number of
370 DMA address entries returned.
371
372 ::
373
374 void
375 dma_sync_single_for_cpu(struct device *dev, dma_addr_t dma_handle,
376 size_t size,
377 enum dma_data_direction direction)
378
379 void
380 dma_sync_single_for_device(struct device *dev, dma_addr_t dma_handle,
381 size_t size,
382 enum dma_data_direction direction)
383
384 void
385 dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
386 int nents,
387 enum dma_data_direction direction)
388
389 void
390 dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
391 int nents,
392 enum dma_data_direction direction)
393
394 Synchronise a single contiguous or scatter/gather mapping for the CPU
395 and device. With the sync_sg API, all the parameters must be the same
396 as those passed into the sg mapping API. With the sync_single API,
397 you can use dma_handle and size parameters that aren't identical to
398 those passed into the single mapping API to do a partial sync.
399
400
401 .. note::
402
403 You must do this:
404
405 - Before reading values that have been written by DMA from the device
406 (use the DMA_FROM_DEVICE direction)
407 - After writing values that will be written to the device using DMA
408 (use the DMA_TO_DEVICE) direction
409 - before *and* after handing memory to the device if the memory is
410 DMA_BIDIRECTIONAL
411
412 See also dma_map_single().
413
414 ::
415
416 dma_addr_t
417 dma_map_single_attrs(struct device *dev, void *cpu_addr, size_t size,
418 enum dma_data_direction dir,
419 unsigned long attrs)
420
421 void
422 dma_unmap_single_attrs(struct device *dev, dma_addr_t dma_addr,
423 size_t size, enum dma_data_direction dir,
424 unsigned long attrs)
425
426 int
427 dma_map_sg_attrs(struct device *dev, struct scatterlist *sgl,
428 int nents, enum dma_data_direction dir,
429 unsigned long attrs)
430
431 void
432 dma_unmap_sg_attrs(struct device *dev, struct scatterlist *sgl,
433 int nents, enum dma_data_direction dir,
434 unsigned long attrs)
435
436 The four functions above are just like the counterpart functions
437 without the _attrs suffixes, except that they pass an optional
438 dma_attrs.
439
440 The interpretation of DMA attributes is architecture-specific, and
441 each attribute should be documented in
442 Documentation/core-api/dma-attributes.rst.
443
444 If dma_attrs are 0, the semantics of each of these functions
445 is identical to those of the corresponding function
446 without the _attrs suffix. As a result dma_map_single_attrs()
447 can generally replace dma_map_single(), etc.
448
449 As an example of the use of the ``*_attrs`` functions, here's how
450 you could pass an attribute DMA_ATTR_FOO when mapping memory
451 for DMA::
452
453 #include <linux/dma-mapping.h>
454 /* DMA_ATTR_FOO should be defined in linux/dma-mapping.h and
455 * documented in Documentation/core-api/dma-attributes.rst */
456 ...
457
458 unsigned long attr;
459 attr |= DMA_ATTR_FOO;
460 ....
461 n = dma_map_sg_attrs(dev, sg, nents, DMA_TO_DEVICE, attr);
462 ....
463
464 Architectures that care about DMA_ATTR_FOO would check for its
465 presence in their implementations of the mapping and unmapping
466 routines, e.g.:::
467
468 void whizco_dma_map_sg_attrs(struct device *dev, dma_addr_t dma_addr,
469 size_t size, enum dma_data_direction dir,
470 unsigned long attrs)
471 {
472 ....
473 if (attrs & DMA_ATTR_FOO)
474 /* twizzle the frobnozzle */
475 ....
476 }
477
478 Part Ie - IOVA-based DMA mappings
479 ---------------------------------
480
481 These APIs allow a very efficient mapping when using an IOMMU. They are an
482 optional path that requires extra code and are only recommended for drivers
483 where DMA mapping performance, or the space usage for storing the DMA addresses
484 matter. All the considerations from the previous section apply here as well.
485
486 ::
487
488 bool dma_iova_try_alloc(struct device *dev, struct dma_iova_state *state,
489 phys_addr_t phys, size_t size);
490
491 Is used to try to allocate IOVA space for mapping operation. If it returns
492 false this API can't be used for the given device and the normal streaming
493 DMA mapping API should be used. The ``struct dma_iova_state`` is allocated
494 by the driver and must be kept around until unmap time.
495
496 ::
497
498 static inline bool dma_use_iova(struct dma_iova_state *state)
499
500 Can be used by the driver to check if the IOVA-based API is used after a
501 call to dma_iova_try_alloc. This can be useful in the unmap path.
502
503 ::
504
505 int dma_iova_link(struct device *dev, struct dma_iova_state *state,
506 phys_addr_t phys, size_t offset, size_t size,
507 enum dma_data_direction dir, unsigned long attrs);
508
509 Is used to link ranges to the IOVA previously allocated. The start of all
510 but the first call to dma_iova_link for a given state must be aligned
511 to the DMA merge boundary returned by ``dma_get_merge_boundary())``, and
512 the size of all but the last range must be aligned to the DMA merge boundary
513 as well.
514
515 ::
516
517 int dma_iova_sync(struct device *dev, struct dma_iova_state *state,
518 size_t offset, size_t size);
519
520 Must be called to sync the IOMMU page tables for IOVA-range mapped by one or
521 more calls to ``dma_iova_link()``.
522
523 For drivers that use a one-shot mapping, all ranges can be unmapped and the
524 IOVA freed by calling:
525
526 ::
527
528 void dma_iova_destroy(struct device *dev, struct dma_iova_state *state,
529 size_t mapped_len, enum dma_data_direction dir,
530 unsigned long attrs);
531
532 Alternatively drivers can dynamically manage the IOVA space by unmapping
533 and mapping individual regions. In that case
534
535 ::
536
537 void dma_iova_unlink(struct device *dev, struct dma_iova_state *state,
538 size_t offset, size_t size, enum dma_data_direction dir,
539 unsigned long attrs);
540
541 is used to unmap a range previously mapped, and
542
543 ::
544
545 void dma_iova_free(struct device *dev, struct dma_iova_state *state);
546
547 is used to free the IOVA space. All regions must have been unmapped using
548 ``dma_iova_unlink()`` before calling ``dma_iova_free()``.
549
550 Part II - Non-coherent DMA allocations
551 --------------------------------------
552
553 These APIs allow to allocate pages that are guaranteed to be DMA addressable
554 by the passed in device, but which need explicit management of memory ownership
555 for the kernel vs the device.
556
557 If you don't understand how cache line coherency works between a processor and
558 an I/O device, you should not be using this part of the API.
559
560 ::
561
562 struct page *
563 dma_alloc_pages(struct device *dev, size_t size, dma_addr_t *dma_handle,
564 enum dma_data_direction dir, gfp_t gfp)
565
566 This routine allocates a region of <size> bytes of non-coherent memory. It
567 returns a pointer to first struct page for the region, or NULL if the
568 allocation failed. The resulting struct page can be used for everything a
569 struct page is suitable for.
570
571 It also returns a <dma_handle> which may be cast to an unsigned integer the
572 same width as the bus and given to the device as the DMA address base of
573 the region.
574
575 The dir parameter specified if data is read and/or written by the device,
576 see dma_map_single() for details.
577
578 The gfp parameter allows the caller to specify the ``GFP_`` flags (see
579 kmalloc()) for the allocation, but rejects flags used to specify a memory
580 zone such as GFP_DMA or GFP_HIGHMEM.
581
582 Before giving the memory to the device, dma_sync_single_for_device() needs
583 to be called, and before reading memory written by the device,
584 dma_sync_single_for_cpu(), just like for streaming DMA mappings that are
585 reused.
586
587 ::
588
589 void
590 dma_free_pages(struct device *dev, size_t size, struct page *page,
591 dma_addr_t dma_handle, enum dma_data_direction dir)
592
593 Free a region of memory previously allocated using dma_alloc_pages().
594 dev, size, dma_handle and dir must all be the same as those passed into
595 dma_alloc_pages(). page must be the pointer returned by dma_alloc_pages().
596
597 ::
598
599 int
600 dma_mmap_pages(struct device *dev, struct vm_area_struct *vma,
601 size_t size, struct page *page)
602
603 Map an allocation returned from dma_alloc_pages() into a user address space.
604 dev and size must be the same as those passed into dma_alloc_pages().
605 page must be the pointer returned by dma_alloc_pages().
606
607 ::
608
609 void *
610 dma_alloc_noncoherent(struct device *dev, size_t size,
611 dma_addr_t *dma_handle, enum dma_data_direction dir,
612 gfp_t gfp)
613
614 This routine is a convenient wrapper around dma_alloc_pages that returns the
615 kernel virtual address for the allocated memory instead of the page structure.
616
617 ::
618
619 void
620 dma_free_noncoherent(struct device *dev, size_t size, void *cpu_addr,
621 dma_addr_t dma_handle, enum dma_data_direction dir)
622
623 Free a region of memory previously allocated using dma_alloc_noncoherent().
624 dev, size, dma_handle and dir must all be the same as those passed into
625 dma_alloc_noncoherent(). cpu_addr must be the virtual address returned by
626 dma_alloc_noncoherent().
627
628 ::
629
630 struct sg_table *
631 dma_alloc_noncontiguous(struct device *dev, size_t size,
632 enum dma_data_direction dir, gfp_t gfp,
633 unsigned long attrs);
634
635 This routine allocates <size> bytes of non-coherent and possibly non-contiguous
636 memory. It returns a pointer to struct sg_table that describes the allocated
637 and DMA mapped memory, or NULL if the allocation failed. The resulting memory
638 can be used for struct page mapped into a scatterlist are suitable for.
639
640 The return sg_table is guaranteed to have 1 single DMA mapped segment as
641 indicated by sgt->nents, but it might have multiple CPU side segments as
642 indicated by sgt->orig_nents.
643
644 The dir parameter specified if data is read and/or written by the device,
645 see dma_map_single() for details.
646
647 The gfp parameter allows the caller to specify the ``GFP_`` flags (see
648 kmalloc()) for the allocation, but rejects flags used to specify a memory
649 zone such as GFP_DMA or GFP_HIGHMEM.
650
651 The attrs argument must be either 0 or DMA_ATTR_ALLOC_SINGLE_PAGES.
652
653 Before giving the memory to the device, dma_sync_sgtable_for_device() needs
654 to be called, and before reading memory written by the device,
655 dma_sync_sgtable_for_cpu(), just like for streaming DMA mappings that are
656 reused.
657
658 ::
659
660 void
661 dma_free_noncontiguous(struct device *dev, size_t size,
662 struct sg_table *sgt,
663 enum dma_data_direction dir)
664
665 Free memory previously allocated using dma_alloc_noncontiguous(). dev, size,
666 and dir must all be the same as those passed into dma_alloc_noncontiguous().
667 sgt must be the pointer returned by dma_alloc_noncontiguous().
668
669 ::
670
671 void *
672 dma_vmap_noncontiguous(struct device *dev, size_t size,
673 struct sg_table *sgt)
674
675 Return a contiguous kernel mapping for an allocation returned from
676 dma_alloc_noncontiguous(). dev and size must be the same as those passed into
677 dma_alloc_noncontiguous(). sgt must be the pointer returned by
678 dma_alloc_noncontiguous().
679
680 Once a non-contiguous allocation is mapped using this function, the
681 flush_kernel_vmap_range() and invalidate_kernel_vmap_range() APIs must be used
682 to manage the coherency between the kernel mapping, the device and user space
683 mappings (if any).
684
685 ::
686
687 void
688 dma_vunmap_noncontiguous(struct device *dev, void *vaddr)
689
690 Unmap a kernel mapping returned by dma_vmap_noncontiguous(). dev must be the
691 same the one passed into dma_alloc_noncontiguous(). vaddr must be the pointer
692 returned by dma_vmap_noncontiguous().
693
694
695 ::
696
697 int
698 dma_mmap_noncontiguous(struct device *dev, struct vm_area_struct *vma,
699 size_t size, struct sg_table *sgt)
700
701 Map an allocation returned from dma_alloc_noncontiguous() into a user address
702 space. dev and size must be the same as those passed into
703 dma_alloc_noncontiguous(). sgt must be the pointer returned by
704 dma_alloc_noncontiguous().
705
706 ::
707
708 int
709 dma_get_cache_alignment(void)
710
711 Returns the processor cache alignment. This is the absolute minimum
712 alignment *and* width that you must observe when either mapping
713 memory or doing partial flushes.
714
715 .. note::
716
717 This API may return a number *larger* than the actual cache
718 line, but it will guarantee that one or more cache lines fit exactly
719 into the width returned by this call. It will also always be a power
720 of two for easy alignment.
721
722
723 Part III - Debug drivers use of the DMA API
724 -------------------------------------------
725
726 The DMA API as described above has some constraints. DMA addresses must be
727 released with the corresponding function with the same size for example. With
728 the advent of hardware IOMMUs it becomes more and more important that drivers
729 do not violate those constraints. In the worst case such a violation can
730 result in data corruption up to destroyed filesystems.
731
732 To debug drivers and find bugs in the usage of the DMA API checking code can
733 be compiled into the kernel which will tell the developer about those
734 violations. If your architecture supports it you can select the "Enable
735 debugging of DMA API usage" option in your kernel configuration. Enabling this
736 option has a performance impact. Do not enable it in production kernels.
737
738 If you boot the resulting kernel will contain code which does some bookkeeping
739 about what DMA memory was allocated for which device. If this code detects an
740 error it prints a warning message with some details into your kernel log. An
741 example warning message may look like this::
742
743 WARNING: at /data2/repos/linux-2.6-iommu/lib/dma-debug.c:448
744 check_unmap+0x203/0x490()
745 Hardware name:
746 forcedeth 0000:00:08.0: DMA-API: device driver frees DMA memory with wrong
747 function [device address=0x00000000640444be] [size=66 bytes] [mapped as
748 single] [unmapped as page]
749 Modules linked in: nfsd exportfs bridge stp llc r8169
750 Pid: 0, comm: swapper Tainted: G W 2.6.28-dmatest-09289-g8bb99c0 #1
751 Call Trace:
752 <IRQ> [<ffffffff80240b22>] warn_slowpath+0xf2/0x130
753 [<ffffffff80647b70>] _spin_unlock+0x10/0x30
754 [<ffffffff80537e75>] usb_hcd_link_urb_to_ep+0x75/0xc0
755 [<ffffffff80647c22>] _spin_unlock_irqrestore+0x12/0x40
756 [<ffffffff8055347f>] ohci_urb_enqueue+0x19f/0x7c0
757 [<ffffffff80252f96>] queue_work+0x56/0x60
758 [<ffffffff80237e10>] enqueue_task_fair+0x20/0x50
759 [<ffffffff80539279>] usb_hcd_submit_urb+0x379/0xbc0
760 [<ffffffff803b78c3>] cpumask_next_and+0x23/0x40
761 [<ffffffff80235177>] find_busiest_group+0x207/0x8a0
762 [<ffffffff8064784f>] _spin_lock_irqsave+0x1f/0x50
763 [<ffffffff803c7ea3>] check_unmap+0x203/0x490
764 [<ffffffff803c8259>] debug_dma_unmap_phys+0x49/0x50
765 [<ffffffff80485f26>] nv_tx_done_optimized+0xc6/0x2c0
766 [<ffffffff80486c13>] nv_nic_irq_optimized+0x73/0x2b0
767 [<ffffffff8026df84>] handle_IRQ_event+0x34/0x70
768 [<ffffffff8026ffe9>] handle_edge_irq+0xc9/0x150
769 [<ffffffff8020e3ab>] do_IRQ+0xcb/0x1c0
770 [<ffffffff8020c093>] ret_from_intr+0x0/0xa
771 <EOI> <4>---[ end trace f6435a98e2a38c0e ]---
772
773 The driver developer can find the driver and the device including a stacktrace
774 of the DMA API call which caused this warning.
775
776 Per default only the first error will result in a warning message. All other
777 errors will only silently counted. This limitation exist to prevent the code
778 from flooding your kernel log. To support debugging a device driver this can
779 be disabled via debugfs. See the debugfs interface documentation below for
780 details.
781
782 The debugfs directory for the DMA API debugging code is called dma-api/. In
783 this directory the following files can currently be found:
784
785 =============================== ===============================================
786 dma-api/all_errors This file contains a numeric value. If this
787 value is not equal to zero the debugging code
788 will print a warning for every error it finds
789 into the kernel log. Be careful with this
790 option, as it can easily flood your logs.
791
792 dma-api/disabled This read-only file contains the character 'Y'
793 if the debugging code is disabled. This can
794 happen when it runs out of memory or if it was
795 disabled at boot time
796
797 dma-api/dump This read-only file contains current DMA
798 mappings.
799
800 dma-api/error_count This file is read-only and shows the total
801 numbers of errors found.
802
803 dma-api/num_errors The number in this file shows how many
804 warnings will be printed to the kernel log
805 before it stops. This number is initialized to
806 one at system boot and be set by writing into
807 this file
808
809 dma-api/min_free_entries This read-only file can be read to get the
810 minimum number of free dma_debug_entries the
811 allocator has ever seen. If this value goes
812 down to zero the code will attempt to increase
813 nr_total_entries to compensate.
814
815 dma-api/num_free_entries The current number of free dma_debug_entries
816 in the allocator.
817
818 dma-api/nr_total_entries The total number of dma_debug_entries in the
819 allocator, both free and used.
820
821 dma-api/driver_filter You can write a name of a driver into this file
822 to limit the debug output to requests from that
823 particular driver. Write an empty string to
824 that file to disable the filter and see
825 all errors again.
826 =============================== ===============================================
827
828 If you have this code compiled into your kernel it will be enabled by default.
829 If you want to boot without the bookkeeping anyway you can provide
830 'dma_debug=off' as a boot parameter. This will disable DMA API debugging.
831 Notice that you can not enable it again at runtime. You have to reboot to do
832 so.
833
834 If you want to see debug messages only for a special device driver you can
835 specify the dma_debug_driver=<drivername> parameter. This will enable the
836 driver filter at boot time. The debug code will only print errors for that
837 driver afterwards. This filter can be disabled or changed later using debugfs.
838
839 When the code disables itself at runtime this is most likely because it ran
840 out of dma_debug_entries and was unable to allocate more on-demand. 65536
841 entries are preallocated at boot - if this is too low for you boot with
842 'dma_debug_entries=<your_desired_number>' to overwrite the default. Note
843 that the code allocates entries in batches, so the exact number of
844 preallocated entries may be greater than the actual number requested. The
845 code will print to the kernel log each time it has dynamically allocated
846 as many entries as were initially preallocated. This is to indicate that a
847 larger preallocation size may be appropriate, or if it happens continually
848 that a driver may be leaking mappings.
849
850 ::
851
852 void
853 debug_dma_mapping_error(struct device *dev, dma_addr_t dma_addr);
854
855 dma-debug interface debug_dma_mapping_error() to debug drivers that fail
856 to check DMA mapping errors on addresses returned by dma_map_single() and
857 dma_map_page() interfaces. This interface clears a flag set by
858 debug_dma_map_phys() to indicate that dma_mapping_error() has been called by
859 the driver. When driver does unmap, debug_dma_unmap() checks the flag and if
860 this flag is still set, prints warning message that includes call trace that
861 leads up to the unmap. This interface can be called from dma_mapping_error()
862 routines to enable DMA mapping error check debugging.
863
864 Functions and structures
865 ========================
866
867 .. kernel-doc:: include/linux/scatterlist.h
868 .. kernel-doc:: lib/scatterlist.c
869

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

Generic device를 사용하는 dynamic DMA mapping

1-15

Dynamic DMA mapping using the generic device (generic device를 사용하는 동적 DMA mapping)

저자는 James E.J. Bottomley <[email protected]>입니다.

이 문서는 DMA API를 설명합니다. 더 쉬운 소개와 실제 예제는 `Documentation/core-api/dma-api-howto.rst`를 참고하십시오.

API는 두 부분으로 나뉩니다. Part I은 기본 API를, Part II는 non-coherent memory machine 지원 확장을 설명합니다. Driver가 보통 legacy platform인 non-coherent platform을 반드시 지원해야 한다는 확신이 없다면 Part I의 API만 사용해야 합니다.

Part I 기본 DMA API

16-26

Part I - DMA API

DMA API를 사용하려면 `#include <linux/dma-mapping.h>`가 필요합니다. 이 header는 `dma_addr_t`와 아래 interface를 제공합니다.

`dma_addr_t`는 platform에서 유효한 모든 DMA address를 담을 수 있고 DMA source 또는 target으로 device에 전달할 수 있습니다. CPU physical address space와 DMA address space 사이에 변환이 있을 수 있으므로 CPU가 `dma_addr_t`를 직접 참조할 수는 없습니다.

Part Ia 큰 DMA-coherent buffer

27-73

Part Ia - 큰 DMA-coherent buffer 사용

void *
dma_alloc_coherent(struct device *dev, size_t size,
                   dma_addr_t *dma_handle, gfp_t flag)

Coherent memory는 device나 processor 어느 쪽이 write해도 caching effect를 걱정하지 않고 상대가 즉시 읽을 수 있는 memory입니다. 다만 device에 읽으라고 알리기 전에 processor write buffer를 flush해야 할 수 있습니다.

`dma_alloc_coherent()`는 `size` byte의 coherent memory region을 allocate합니다. 성공하면 processor virtual address space의 pointer를, 실패하면 `NULL`을 반환합니다. 또한 bus와 같은 폭의 unsigned integer로 cast하여 device에 region의 DMA address base로 줄 수 있는 `dma_handle`을 반환합니다.

일부 platform에서 coherent memory는 비용이 크고 최소 allocation 길이가 한 page일 수 있습니다. 요청을 가능한 한 합치는 것이 좋으며 가장 간단한 방법은 아래의 `dma_pool` 호출을 사용하는 것입니다.

`flag` parameter로 allocation의 `GFP_` flag를 지정합니다. 의미는 `kmalloc()`을 참고하십시오. 구현은 `GFP_DMA`처럼 반환 memory 위치에 영향을 주는 flag를 무시할 수 있습니다.

void
dma_free_coherent(struct device *dev, size_t size, void *cpu_addr,
                  dma_addr_t dma_handle)

이 함수는 앞서 allocate한 coherent memory region을 free합니다. `dev`, `size`, `dma_handle`은 `dma_alloc_coherent()`에 전달한 값과 같아야 하며 `cpu_addr`는 그 함수가 반환한 virtual address여야 합니다.

Allocation 함수와 달리 `dma_free_coherent()`는 IRQ가 활성화된 상태에서만 호출할 수 있습니다.

Part Ib 작은 DMA-coherent buffer

74-91

Part Ib - 작은 DMA-coherent buffer 사용

이 DMA API 부분을 사용하려면 `#include <linux/dmapool.h>`가 필요합니다.

많은 driver는 DMA descriptor나 I/O buffer용 작은 DMA-coherent memory region을 많이 필요로 합니다. `dma_alloc_coherent()`로 page 이상 단위로 allocate하는 대신 DMA pool을 사용할 수 있습니다. DMA pool은 `struct kmem_cache`와 비슷하지만 `__get_free_pages()`가 아니라 DMA-coherent allocator를 사용하고, queue head의 N-byte boundary 정렬 같은 hardware alignment constraint를 이해합니다.

공개 API의 kernel-doc은 `mm/dmapool.c`의 exported symbol과 `include/linux/dmapool.h`에서 가져옵니다.

Part Ic DMA 주소 지정 한계

92-183

Part Ic - DMA addressing limitation

DMA mask는 device가 address할 수 있는 영역의 bit mask입니다. Memory region의 DMA address와 mask를 bitwise AND했을 때 address의 bit가 하나도 지워지지 않으면 device가 그 region에 DMA할 수 있습니다.

아래의 DMA mask 설정 함수는 요청한 mask를 device와 함께 사용할 수 없거나 device가 DMA를 수행할 수 없으면 실패할 수 있습니다.

int
dma_set_mask_and_coherent(struct device *dev, u64 mask)

`dma_set_mask_and_coherent()`는 streaming과 coherent DMA mask를 모두 갱신하며 성공하면 0, 실패하면 음수 error를 반환합니다.

int
dma_set_mask(struct device *dev, u64 mask)

`dma_set_mask()`는 streaming DMA mask만 갱신하며 성공하면 0, 실패하면 음수 error를 반환합니다.

int
dma_set_coherent_mask(struct device *dev, u64 mask)

`dma_set_coherent_mask()`는 coherent DMA mask만 갱신하며 성공하면 0, 실패하면 음수 error를 반환합니다.

u64
dma_get_required_mask(struct device *dev)

`dma_get_required_mask()`는 platform이 효율적으로 동작하는 데 필요한 mask를 반환합니다. 보통 전체 memory를 덮는 최소 mask이며, variable descriptor size를 지원하는 driver는 이를 보고 더 작은 descriptor를 선택할 수 있습니다. 이 조회는 현재 mask를 바꾸지 않으므로 활용하려면 반환값으로 `dma_set_mask()`를 호출해야 합니다.

size_t
dma_max_mapping_size(struct device *dev);

`dma_max_mapping_size()`는 device에서 가능한 mapping의 최대 size를 반환합니다. `dma_map_single()`, `dma_map_page()` 같은 mapping 함수의 size parameter가 이 값을 넘으면 안 됩니다.

size_t
dma_opt_mapping_size(struct device *dev);

`dma_opt_mapping_size()`는 최적 mapping의 최대 size를 반환합니다. 일부 상황에서 큰 buffer mapping은 훨씬 오래 걸리며, 짧게 유지되는 고속 streaming mapping에서는 준비 시간이 전체 request lifetime의 상당 부분일 수 있습니다. 큰 request를 나누어도 성능 손해가 크지 않다면 전체 DMA streaming mapping 길이를 반환값 이하로 제한하는 것이 좋습니다.

bool
dma_need_sync(struct device *dev, dma_addr_t dma_addr);

`dma_need_sync()`는 memory ownership 전환에 `dma_sync_single_for_{device,cpu}` 호출이 필요하면 `%true`, 생략할 수 있으면 `%false`를 반환합니다.

unsigned long
dma_get_merge_boundary(struct device *dev);

`dma_get_merge_boundary()`는 DMA merge boundary를 반환합니다. Device가 DMA address segment를 전혀 merge할 수 없으면 0을 반환합니다.

Part Id streaming single mapping과 방향

184-267

Part Id - Streaming DMA mapping

Streaming DMA는 기존 buffer를 DMA transfer용으로 mapping하고 끝나면 unmap합니다. Map 함수는 성공이 보장되지 않으므로 반환값을 검사해야 합니다.

Device나 연결 bus bridge의 DMA mask 밖에 있는 memory는 mapping이 실패할 수 있습니다. Streaming DMA 함수는 I/O DMA address를 physical memory address로 mapping하는 IOMMU를 사용하거나, kernel에 `SWIOTLB`가 구성되어 있으면 bounce buffer로 data를 복사해 제약을 극복하려 합니다. 하지만 이 기능들이 항상 제공되는 것은 아니며 다른 이유로도 실패할 수 있습니다. 특히 DMA mask가 32-bit보다 작다면 driver는 buffer의 physical memory 위치를 주의해야 합니다.

dma_addr_t
dma_map_single(struct device *dev, void *cpu_addr, size_t size,
               enum dma_data_direction direction)

`dma_map_single()`은 processor virtual memory 일부를 device가 접근할 수 있도록 mapping하고 그 memory의 DMA address를 반환합니다.

DMA API의 direction은 강한 type의 enumerator입니다.

Direction의미
DMA_NONE방향 없음, debugging에 사용
DMA_TO_DEVICEMemory에서 device로 data 이동
DMA_FROM_DEVICEDevice에서 memory로 data 이동
DMA_BIDIRECTIONAL방향을 알 수 없음

연속된 kernel virtual space가 physical memory에서도 연속이라는 보장은 없습니다. 이 API는 scatter/gather 기능이 없으므로 물리적으로 연속되지 않은 memory를 mapping하면 실패합니다. 따라서 `kmalloc()`처럼 physical continuity를 보장하는 source에서 얻은 memory를 사용해야 합니다.

Memory coherency 단위는 cache line width입니다. Mapping region은 서로 다른 region이 같은 cache line을 공유하지 않도록 cache line boundary에서 정확히 시작하고 끝나야 합니다. Compile time에 cache line size를 모를 수 있어 API가 강제하지 않으므로 runtime size를 별도로 처리하지 않는 driver는 page boundary에서 시작하고 끝나는 virtual region만 mapping하는 것이 좋습니다. Page boundary는 cache line boundary이기도 합니다.

`DMA_TO_DEVICE` synchronization은 software가 memory region을 마지막으로 수정한 뒤 device에 넘기기 전에 수행합니다. 그 뒤 해당 memory는 device 관점에서 read-only로 취급해야 하며 device가 쓸 수 있다면 `DMA_BIDIRECTIONAL`을 사용해야 합니다.

`DMA_FROM_DEVICE` synchronization은 driver가 device가 바꿨을 수 있는 data에 접근하기 전에 수행합니다. 이 memory는 driver 관점에서 read-only로 취급해야 하며 driver가 써야 한다면 `DMA_BIDIRECTIONAL`을 사용합니다.

`DMA_BIDIRECTIONAL`은 memory를 device에 넘기기 전에 driver가 수정했는지, device도 수정할지 모두 확실하지 않은 경우입니다. 따라서 device에 넘기기 전 processor의 변경을 flush하기 위해 한 번, device 사용 뒤 접근하기 전 device가 바꾼 data로 processor cache line을 갱신하기 위해 한 번, 항상 두 번 sync해야 합니다.

Streaming unmap, page, resource와 오류 API

268-318
void
dma_unmap_single(struct device *dev, dma_addr_t dma_addr, size_t size,
                 enum dma_data_direction direction)

`dma_unmap_single()`은 앞서 mapping한 region을 unmap합니다. 모든 parameter는 `dma_map_single()`에 전달하고 반환받은 값과 동일해야 합니다.

dma_addr_t
dma_map_page(struct device *dev, struct page *page,
             unsigned long offset, size_t size,
             enum dma_data_direction direction)

void
dma_unmap_page(struct device *dev, dma_addr_t dma_address, size_t size,
               enum dma_data_direction direction)

`dma_map_page()`와 `dma_unmap_page()`는 page를 mapping하고 unmap하는 API입니다. 다른 mapping API의 모든 note와 warning이 적용됩니다. `offset`과 `size`로 partial page mapping을 할 수 있지만 cache width를 정확히 아는 경우가 아니라면 사용하지 않는 것이 좋습니다.

dma_addr_t
dma_map_resource(struct device *dev, phys_addr_t phys_addr, size_t size,
                 enum dma_data_direction dir, unsigned long attrs)

void
dma_unmap_resource(struct device *dev, dma_addr_t addr, size_t size,
                   enum dma_data_direction dir, unsigned long attrs)

`dma_map_resource()`와 `dma_unmap_resource()`는 MMIO resource를 mapping하고 unmap합니다. 다른 mapping API의 note와 warning이 모두 적용되며 device MMIO resource에만 사용해야 하고 RAM mapping은 허용되지 않습니다.

int
dma_mapping_error(struct device *dev, dma_addr_t dma_addr)

`dma_map_single()`, `dma_map_page()`, `dma_map_resource()`는 mapping 생성에 실패할 수 있습니다. Driver는 반환된 DMA address를 `dma_mapping_error()`로 검사합니다. 0이 아닌 반환값은 mapping 실패를 뜻하므로 현재 DMA mapping 사용량을 줄이거나 지연 후 재시도하는 등 적절히 처리해야 합니다.

Streaming scatter/gather mapping

319-371
int
dma_map_sg(struct device *dev, struct scatterlist *sg,
           int nents, enum dma_data_direction direction)

`dma_map_sg()`는 scatter/gather list를 DMA용으로 mapping하고 DMA address segment 수를 반환합니다. 연속된 sglist entry를 IOMMU로 merge하거나 인접 segment가 우연히 물리적으로 연속이면 반환값이 입력 `nents`보다 작을 수 있습니다.

한 번 mapping한 `sg`는 다시 mapping할 수 없습니다. Mapping 과정은 `sg` 안의 정보를 파괴할 수 있습니다.

`dma_map_sg()`도 실패할 수 있으며 0을 반환합니다. Driver는 반드시 처리해야 합니다. Block driver라면 아무것도 하지 않아 filesystem을 손상시키는 것보다 request를 abort하거나 심지어 oops하는 편이 낫습니다.

Scatterlist mapping 결과는 다음처럼 사용합니다.

int i, count = dma_map_sg(dev, sglist, nents, direction);
struct scatterlist *sg;

for_each_sg(sglist, sg, count, i) {
        hw_address[i] = sg_dma_address(sg);
        hw_len[i] = sg_dma_len(sg);
}

`nents`는 `sglist` entry 수입니다. 구현은 여러 연속 entry를 하나로 merge할 수 있고 반환값은 실제 mapping된 sg entry 수이며 실패 시 0입니다. 반환된 `count`만큼 순회하면서 기존 `sg->address`, `sg->length` 대신 `sg_dma_address()`와 `sg_dma_len()`을 사용합니다.

void
dma_unmap_sg(struct device *dev, struct scatterlist *sg,
             int nents, enum dma_data_direction direction)

`dma_unmap_sg()`는 앞서 mapping한 scatter/gather list를 unmap하며 parameter는 mapping API에 전달한 것과 같아야 합니다. 특히 `nents`는 반환된 DMA address entry 수가 아니라 입력으로 전달한 수여야 합니다.

Streaming mapping 동기화

372-413
void
dma_sync_single_for_cpu(struct device *dev, dma_addr_t dma_handle,
                        size_t size,
                        enum dma_data_direction direction)

void
dma_sync_single_for_device(struct device *dev, dma_addr_t dma_handle,
                           size_t size,
                           enum dma_data_direction direction)

void
dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
                    int nents,
                    enum dma_data_direction direction)

void
dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
                       int nents,
                       enum dma_data_direction direction)

이 함수들은 single contiguous 또는 scatter/gather mapping을 CPU와 device에 맞게 synchronize합니다. `sync_sg` API의 모든 parameter는 sg mapping API에 전달한 것과 같아야 합니다. `sync_single` API는 single mapping 때와 다른 `dma_handle`과 `size`로 partial sync를 수행할 수 있습니다.

다음 시점에는 반드시 synchronize해야 합니다.

  • Device가 DMA로 쓴 값을 읽기 전에는 DMA_FROM_DEVICE direction을 사용합니다.
  • DMA로 device에 보낼 값을 쓴 뒤에는 DMA_TO_DEVICE direction을 사용합니다.
  • Memory가 DMA_BIDIRECTIONAL이면 device에 넘기기 전과 돌려받은 뒤 모두 수행합니다.

관련 규칙은 `dma_map_single()` 설명도 참고하십시오.

DMA attribute가 있는 mapping

414-477
dma_addr_t
dma_map_single_attrs(struct device *dev, void *cpu_addr, size_t size,
                     enum dma_data_direction dir,
                     unsigned long attrs)

void
dma_unmap_single_attrs(struct device *dev, dma_addr_t dma_addr,
                       size_t size, enum dma_data_direction dir,
                       unsigned long attrs)

int
dma_map_sg_attrs(struct device *dev, struct scatterlist *sgl,
                 int nents, enum dma_data_direction dir,
                 unsigned long attrs)

void
dma_unmap_sg_attrs(struct device *dev, struct scatterlist *sgl,
                   int nents, enum dma_data_direction dir,
                   unsigned long attrs)

위 네 함수는 `_attrs` suffix가 없는 대응 함수와 같지만 optional `dma_attrs`를 추가로 전달합니다.

DMA attribute 해석은 architecture마다 다르며 각 attribute는 `Documentation/core-api/dma-attributes.rst`에 문서화해야 합니다.

`dma_attrs`가 0이면 각 함수의 의미는 `_attrs` 없는 대응 함수와 같습니다. 따라서 일반적으로 `dma_map_single_attrs()`가 `dma_map_single()`을 대체할 수 있습니다.

`*_attrs` 함수로 memory를 DMA mapping할 때 `DMA_ATTR_FOO` attribute를 전달하는 예는 다음과 같습니다.

#include <linux/dma-mapping.h>
/* DMA_ATTR_FOO should be defined in linux/dma-mapping.h and
* documented in Documentation/core-api/dma-attributes.rst */
...

        unsigned long attr;
        attr |= DMA_ATTR_FOO;
        ....
        n = dma_map_sg_attrs(dev, sg, nents, DMA_TO_DEVICE, attr);
        ....

`DMA_ATTR_FOO`를 고려하는 architecture는 mapping 및 unmapping 구현에서 attribute 존재를 다음처럼 검사합니다.

void whizco_dma_map_sg_attrs(struct device *dev, dma_addr_t dma_addr,
                             size_t size, enum dma_data_direction dir,
                             unsigned long attrs)
{
        ....
        if (attrs & DMA_ATTR_FOO)
                /* twizzle the frobnozzle */
        ....
}

Part Ie IOVA 기반 DMA mapping

478-549

Part Ie - IOVA-based DMA mapping

이 API는 IOMMU 사용 시 매우 효율적인 mapping을 제공합니다. 추가 code가 필요한 optional path이며 DMA mapping 성능이나 DMA address 저장 공간이 중요한 driver에만 권장합니다. 앞 절의 모든 고려 사항이 그대로 적용됩니다.

bool dma_iova_try_alloc(struct device *dev, struct dma_iova_state *state,
            phys_addr_t phys, size_t size);

`dma_iova_try_alloc()`은 mapping operation을 위한 IOVA space allocation을 시도합니다. `false`면 해당 device에 이 API를 사용할 수 없으므로 일반 streaming DMA mapping API를 사용합니다. `struct dma_iova_state`는 driver가 allocate하고 unmap 때까지 유지해야 합니다.

static inline bool dma_use_iova(struct dma_iova_state *state)

`dma_use_iova()`는 `dma_iova_try_alloc()` 호출 뒤 IOVA 기반 API가 사용 중인지 driver가 확인합니다. Unmap path에서 유용합니다.

int dma_iova_link(struct device *dev, struct dma_iova_state *state,
            phys_addr_t phys, size_t offset, size_t size,
            enum dma_data_direction dir, unsigned long attrs);

`dma_iova_link()`는 앞서 allocate한 IOVA에 range를 연결합니다. 한 state에 대한 첫 호출을 제외한 모든 range 시작점은 `dma_get_merge_boundary()`가 반환한 DMA merge boundary에 맞춰야 하며 마지막을 제외한 모든 range size도 같은 boundary에 맞춰야 합니다.

int dma_iova_sync(struct device *dev, struct dma_iova_state *state,
            size_t offset, size_t size);

`dma_iova_sync()`는 하나 이상의 `dma_iova_link()` 호출로 mapping한 IOVA range의 IOMMU page table을 synchronize하기 위해 호출해야 합니다.

One-shot mapping driver는 다음 함수로 모든 range를 unmap하고 IOVA를 free할 수 있습니다.

void dma_iova_destroy(struct device *dev, struct dma_iova_state *state,
             size_t mapped_len, enum dma_data_direction dir,
             unsigned long attrs);

또는 개별 region을 mapping/unmapping하여 IOVA space를 동적으로 관리할 수 있습니다. 앞서 mapping한 range는 다음으로 unmap합니다.

void dma_iova_unlink(struct device *dev, struct dma_iova_state *state,
            size_t offset, size_t size, enum dma_data_direction dir,
            unsigned long attrs);

IOVA space는 다음으로 free합니다.

void dma_iova_free(struct device *dev, struct dma_iova_state *state);

`dma_iova_free()` 호출 전에 모든 region을 `dma_iova_unlink()`로 unmap해야 합니다.

Part II non-coherent page allocation

550-626

Part II - Non-coherent DMA allocation

이 API는 주어진 device가 DMA address로 접근할 수 있음을 보장하는 page를 allocate하지만 kernel과 device 사이의 memory ownership을 명시적으로 관리해야 합니다. Processor와 I/O device 사이의 cache line coherency를 이해하지 못한다면 이 API 부분을 사용하면 안 됩니다.

struct page *
dma_alloc_pages(struct device *dev, size_t size, dma_addr_t *dma_handle,
                enum dma_data_direction dir, gfp_t gfp)

`dma_alloc_pages()`는 `size` byte의 non-coherent memory region을 allocate합니다. 성공하면 region의 첫 `struct page` pointer를, 실패하면 `NULL`을 반환합니다. 결과 page는 일반 `struct page` 용도에 사용할 수 있습니다. 함께 반환하는 `dma_handle`은 bus 폭의 unsigned integer로 cast하여 device에 region의 DMA address base로 전달할 수 있습니다.

`dir`은 device가 data를 읽거나 쓰는 방향이며 자세한 내용은 `dma_map_single()`을 참고합니다. `gfp`는 `kmalloc()`과 같은 `GFP_` flag를 지정하지만 `GFP_DMA`, `GFP_HIGHMEM`처럼 memory zone을 고르는 flag는 거부합니다.

Memory를 device에 넘기기 전에 `dma_sync_single_for_device()`를, device가 쓴 memory를 읽기 전에 `dma_sync_single_for_cpu()`를 호출해야 합니다. 재사용하는 streaming DMA mapping과 같은 규칙입니다.

void
dma_free_pages(struct device *dev, size_t size, struct page *page,
                dma_addr_t dma_handle, enum dma_data_direction dir)

`dma_free_pages()`는 `dma_alloc_pages()`가 allocate한 memory를 free합니다. `dev`, `size`, `dma_handle`, `dir`은 allocation 때와 같아야 하고 `page`는 반환받은 pointer여야 합니다.

int
dma_mmap_pages(struct device *dev, struct vm_area_struct *vma,
               size_t size, struct page *page)

`dma_mmap_pages()`는 `dma_alloc_pages()` allocation을 user address space에 mapping합니다. `dev`, `size`, `page`는 allocation 때 사용하거나 반환받은 값과 같아야 합니다.

void *
dma_alloc_noncoherent(struct device *dev, size_t size,
                dma_addr_t *dma_handle, enum dma_data_direction dir,
                gfp_t gfp)

`dma_alloc_noncoherent()`는 `dma_alloc_pages()`의 편의 wrapper로, page structure 대신 allocate한 memory의 kernel virtual address를 반환합니다.

void
dma_free_noncoherent(struct device *dev, size_t size, void *cpu_addr,
                dma_addr_t dma_handle, enum dma_data_direction dir)

`dma_free_noncoherent()`는 앞 함수로 allocate한 memory를 free합니다. 모든 parameter는 allocation 때 전달하거나 반환받은 값과 같아야 합니다.

Non-contiguous allocation과 cache alignment

627-722
struct sg_table *
dma_alloc_noncontiguous(struct device *dev, size_t size,
                        enum dma_data_direction dir, gfp_t gfp,
                        unsigned long attrs);

`dma_alloc_noncontiguous()`는 `size` byte의 non-coherent하고 물리적으로 연속되지 않을 수 있는 memory를 allocate합니다. 성공하면 allocate 및 DMA mapping된 memory를 설명하는 `struct sg_table` pointer를, 실패하면 `NULL`을 반환합니다.

반환 `sg_table`은 `sgt->nents` 기준으로 DMA mapped segment가 정확히 하나임을 보장하지만 CPU 쪽 segment는 `sgt->orig_nents`가 나타내듯 여러 개일 수 있습니다. `dir`과 `gfp` 규칙은 위와 같고 `attrs`는 0 또는 `DMA_ATTR_ALLOC_SINGLE_PAGES`여야 합니다.

Device에 넘기기 전에 `dma_sync_sgtable_for_device()`를, device가 쓴 memory를 읽기 전에 `dma_sync_sgtable_for_cpu()`를 호출합니다.

void
dma_free_noncontiguous(struct device *dev, size_t size,
                       struct sg_table *sgt,
                       enum dma_data_direction dir)

`dma_free_noncontiguous()`는 앞 함수가 allocate한 memory를 free합니다. `dev`, `size`, `dir`은 같아야 하고 `sgt`는 반환받은 pointer여야 합니다.

void *
dma_vmap_noncontiguous(struct device *dev, size_t size,
        struct sg_table *sgt)

`dma_vmap_noncontiguous()`는 non-contiguous allocation에 대한 contiguous kernel mapping을 반환합니다. Mapping 뒤에는 `flush_kernel_vmap_range()`와 `invalidate_kernel_vmap_range()`를 사용해 kernel mapping, device, user space mapping 사이의 coherency를 관리해야 합니다.

void
dma_vunmap_noncontiguous(struct device *dev, void *vaddr)

`dma_vunmap_noncontiguous()`는 위 함수가 반환한 kernel mapping을 unmap합니다. `dev`는 allocation 때와 같고 `vaddr`는 반환받은 pointer여야 합니다.

int
dma_mmap_noncontiguous(struct device *dev, struct vm_area_struct *vma,
                       size_t size, struct sg_table *sgt)

`dma_mmap_noncontiguous()`는 non-contiguous allocation을 user address space에 mapping하며 `dev`, `size`, `sgt`는 allocation과 일치해야 합니다.

int
dma_get_cache_alignment(void)

`dma_get_cache_alignment()`는 processor cache alignment를 반환합니다. Memory mapping이나 partial flush에서 지켜야 할 절대 최소 alignment이자 width입니다.

이 API는 실제 cache line보다 큰 값을 반환할 수 있지만 하나 이상의 cache line이 반환 width에 정확히 들어맞음을 보장합니다. 쉽게 정렬할 수 있도록 항상 2의 거듭제곱입니다.

Part III DMA API 사용 오류 디버깅

723-781

Part III - Driver의 DMA API 사용 디버깅

DMA API에는 같은 size와 대응 함수로 DMA address를 해제해야 하는 등의 제약이 있습니다. Hardware IOMMU가 보편화되면서 driver가 이를 지키는 일이 더 중요해졌고, 최악에는 filesystem 파괴까지 포함한 data corruption이 생길 수 있습니다.

DMA API 사용 bug를 찾기 위한 검사 code를 kernel에 compile할 수 있습니다. Architecture가 지원하면 kernel configuration에서 `Enable debugging of DMA API usage`를 선택합니다. 성능 영향이 있으므로 production kernel에서는 활성화하지 마십시오.

이 kernel은 어느 device에 어떤 DMA memory가 allocate되었는지 bookkeeping하고 오류를 발견하면 상세 warning을 kernel log에 출력합니다. 예시는 다음과 같습니다.

WARNING: at /data2/repos/linux-2.6-iommu/lib/dma-debug.c:448
        check_unmap+0x203/0x490()
Hardware name:
forcedeth 0000:00:08.0: DMA-API: device driver frees DMA memory with wrong
        function [device address=0x00000000640444be] [size=66 bytes] [mapped as
single] [unmapped as page]
Modules linked in: nfsd exportfs bridge stp llc r8169
Pid: 0, comm: swapper Tainted: G        W  2.6.28-dmatest-09289-g8bb99c0 #1
Call Trace:
<IRQ>  [<ffffffff80240b22>] warn_slowpath+0xf2/0x130
[<ffffffff80647b70>] _spin_unlock+0x10/0x30
[<ffffffff80537e75>] usb_hcd_link_urb_to_ep+0x75/0xc0
[<ffffffff80647c22>] _spin_unlock_irqrestore+0x12/0x40
[<ffffffff8055347f>] ohci_urb_enqueue+0x19f/0x7c0
[<ffffffff80252f96>] queue_work+0x56/0x60
[<ffffffff80237e10>] enqueue_task_fair+0x20/0x50
[<ffffffff80539279>] usb_hcd_submit_urb+0x379/0xbc0
[<ffffffff803b78c3>] cpumask_next_and+0x23/0x40
[<ffffffff80235177>] find_busiest_group+0x207/0x8a0
[<ffffffff8064784f>] _spin_lock_irqsave+0x1f/0x50
[<ffffffff803c7ea3>] check_unmap+0x203/0x490
[<ffffffff803c8259>] debug_dma_unmap_phys+0x49/0x50
[<ffffffff80485f26>] nv_tx_done_optimized+0xc6/0x2c0
[<ffffffff80486c13>] nv_nic_irq_optimized+0x73/0x2b0
[<ffffffff8026df84>] handle_IRQ_event+0x34/0x70
[<ffffffff8026ffe9>] handle_edge_irq+0xc9/0x150
[<ffffffff8020e3ab>] do_IRQ+0xcb/0x1c0
[<ffffffff8020c093>] ret_from_intr+0x0/0xa
<EOI> <4>---[ end trace f6435a98e2a38c0e ]---

Driver developer는 warning을 발생시킨 DMA API 호출의 stack trace와 함께 driver와 device를 찾을 수 있습니다.

기본적으로 첫 오류만 warning message를 만들고 나머지는 조용히 count합니다. Kernel log flooding을 막기 위한 제한이며 driver debugging 중에는 아래 debugfs interface로 해제할 수 있습니다.

DMA API debugfs interface와 boot parameter

782-849

DMA API debugging code의 debugfs directory는 `dma-api/`이며 다음 file을 제공합니다.

파일설명
dma-api/all_errors0이 아니면 발견한 모든 오류를 kernel log에 warning으로 출력합니다. Log flooding에 주의해야 합니다.
dma-api/disabledDebug code가 memory 부족이나 boot 설정으로 비활성화되었으면 읽기 전용 값 Y를 표시합니다.
dma-api/dump현재 DMA mapping을 보여 주는 읽기 전용 file입니다.
dma-api/error_count발견된 전체 오류 수를 보여 주는 읽기 전용 file입니다.
dma-api/num_errorsKernel log에 출력할 warning 수입니다. Boot 때 1이며 값을 쓸 수 있습니다.
dma-api/min_free_entriesAllocator가 관측한 최소 free dma_debug_entries 수입니다. 0이면 nr_total_entries 증가를 시도합니다.
dma-api/num_free_entriesAllocator의 현재 free dma_debug_entries 수입니다.
dma-api/nr_total_entriesFree 및 사용 중 entry를 합한 전체 dma_debug_entries 수입니다.
dma-api/driver_filter특정 driver 이름을 써서 debug output을 제한합니다. 빈 문자열을 쓰면 filter를 끄고 모든 오류를 다시 봅니다.

Code를 kernel에 compile하면 기본 활성화됩니다. Bookkeeping 없이 부팅하려면 `dma_debug=off` boot parameter를 사용합니다. Runtime에는 다시 활성화할 수 없으므로 reboot해야 합니다.

특정 device driver의 debug message만 보려면 `dma_debug_driver=<drivername>` parameter를 사용합니다. Boot 때 driver filter를 활성화하며 이후 debugfs에서 끄거나 바꿀 수 있습니다.

Runtime에 code가 스스로 비활성화되었다면 보통 `dma_debug_entries`가 바닥나 추가 allocate에 실패한 경우입니다. Boot 때 65536개를 preallocate하며 부족하면 `dma_debug_entries=<your_desired_number>`로 기본값을 덮어씁니다. Entry는 batch로 allocate하므로 실제 preallocation 수가 요청보다 클 수 있습니다. 동적 allocation 누계가 최초 preallocation만큼 늘 때마다 kernel log에 알리며, 더 큰 사전 할당이 필요하거나 계속 반복된다면 driver가 mapping을 leak할 수 있음을 뜻합니다.

Mapping 오류 검사 누락 탐지

850-863
void
debug_dma_mapping_error(struct device *dev, dma_addr_t dma_addr);

`debug_dma_mapping_error()`는 `dma_map_single()`과 `dma_map_page()` 반환 주소의 DMA mapping error 검사를 빠뜨린 driver를 디버깅합니다. `debug_dma_map_phys()`가 설정한 flag를 지워 driver가 `dma_mapping_error()`를 호출했음을 표시합니다. Unmap 때 `debug_dma_unmap()`이 flag를 검사하고 그대로 남아 있으면 unmap까지 이어진 call trace를 포함한 warning을 출력합니다. DMA mapping error check debugging을 활성화하도록 `dma_mapping_error()` routine에서 호출할 수 있습니다.

함수와 구조체

864-868

함수와 구조체

공개 함수와 structure의 kernel-doc은 `include/linux/scatterlist.h`와 `lib/scatterlist.c`에서 가져옵니다.