]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/arm/arm/busdma_machdep-v6.c
powerpc/pmap: Minor optimizations to 64-bit booke pmap
[FreeBSD/FreeBSD.git] / sys / arm / arm / busdma_machdep-v6.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2012-2015 Ian Lepore
5  * Copyright (c) 2010 Mark Tinguely
6  * Copyright (c) 2004 Olivier Houchard
7  * Copyright (c) 2002 Peter Grehan
8  * Copyright (c) 1997, 1998 Justin T. Gibbs.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions, and the following disclaimer,
16  *    without modification, immediately at the beginning of the file.
17  * 2. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
24  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *  From i386/busdma_machdep.c 191438 2009-04-23 20:24:19Z jhb
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/malloc.h>
41 #include <sys/bus.h>
42 #include <sys/busdma_bufalloc.h>
43 #include <sys/counter.h>
44 #include <sys/interrupt.h>
45 #include <sys/kernel.h>
46 #include <sys/ktr.h>
47 #include <sys/lock.h>
48 #include <sys/memdesc.h>
49 #include <sys/proc.h>
50 #include <sys/mutex.h>
51 #include <sys/sysctl.h>
52 #include <sys/uio.h>
53
54 #include <vm/vm.h>
55 #include <vm/vm_page.h>
56 #include <vm/vm_map.h>
57 #include <vm/vm_extern.h>
58 #include <vm/vm_kern.h>
59
60 #include <machine/atomic.h>
61 #include <machine/bus.h>
62 #include <machine/cpu.h>
63 #include <machine/md_var.h>
64
65 #define BUSDMA_DCACHE_ALIGN     cpuinfo.dcache_line_size
66 #define BUSDMA_DCACHE_MASK      cpuinfo.dcache_line_mask
67
68 #define MAX_BPAGES              64
69 #define MAX_DMA_SEGMENTS        4096
70 #define BUS_DMA_EXCL_BOUNCE     BUS_DMA_BUS2
71 #define BUS_DMA_ALIGN_BOUNCE    BUS_DMA_BUS3
72 #define BUS_DMA_COULD_BOUNCE    (BUS_DMA_EXCL_BOUNCE | BUS_DMA_ALIGN_BOUNCE)
73 #define BUS_DMA_MIN_ALLOC_COMP  BUS_DMA_BUS4
74
75 struct bounce_zone;
76
77 struct bus_dma_tag {
78         bus_dma_tag_t           parent;
79         bus_size_t              alignment;
80         bus_addr_t              boundary;
81         bus_addr_t              lowaddr;
82         bus_addr_t              highaddr;
83         bus_dma_filter_t        *filter;
84         void                    *filterarg;
85         bus_size_t              maxsize;
86         u_int                   nsegments;
87         bus_size_t              maxsegsz;
88         int                     flags;
89         int                     ref_count;
90         int                     map_count;
91         bus_dma_lock_t          *lockfunc;
92         void                    *lockfuncarg;
93         struct bounce_zone      *bounce_zone;
94 };
95
96 struct bounce_page {
97         vm_offset_t     vaddr;          /* kva of bounce buffer */
98         bus_addr_t      busaddr;        /* Physical address */
99         vm_offset_t     datavaddr;      /* kva of client data */
100         vm_page_t       datapage;       /* physical page of client data */
101         vm_offset_t     dataoffs;       /* page offset of client data */
102         bus_size_t      datacount;      /* client data count */
103         STAILQ_ENTRY(bounce_page) links;
104 };
105
106 struct sync_list {
107         vm_offset_t     vaddr;          /* kva of client data */
108         bus_addr_t      paddr;          /* physical address */
109         vm_page_t       pages;          /* starting page of client data */
110         bus_size_t      datacount;      /* client data count */
111 };
112
113 int busdma_swi_pending;
114
115 struct bounce_zone {
116         STAILQ_ENTRY(bounce_zone) links;
117         STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
118         int             total_bpages;
119         int             free_bpages;
120         int             reserved_bpages;
121         int             active_bpages;
122         int             total_bounced;
123         int             total_deferred;
124         int             map_count;
125         bus_size_t      alignment;
126         bus_addr_t      lowaddr;
127         char            zoneid[8];
128         char            lowaddrid[20];
129         struct sysctl_ctx_list sysctl_tree;
130         struct sysctl_oid *sysctl_tree_top;
131 };
132
133 static struct mtx bounce_lock;
134 static int total_bpages;
135 static int busdma_zonecount;
136 static uint32_t tags_total;
137 static uint32_t maps_total;
138 static uint32_t maps_dmamem;
139 static uint32_t maps_coherent;
140 static counter_u64_t maploads_total;
141 static counter_u64_t maploads_bounced;
142 static counter_u64_t maploads_coherent;
143 static counter_u64_t maploads_dmamem;
144 static counter_u64_t maploads_mbuf;
145 static counter_u64_t maploads_physmem;
146
147 static STAILQ_HEAD(, bounce_zone) bounce_zone_list;
148
149 SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
150 SYSCTL_UINT(_hw_busdma, OID_AUTO, tags_total, CTLFLAG_RD, &tags_total, 0,
151    "Number of active tags");
152 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_total, CTLFLAG_RD, &maps_total, 0,
153    "Number of active maps");
154 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_dmamem, CTLFLAG_RD, &maps_dmamem, 0,
155    "Number of active maps for bus_dmamem_alloc buffers");
156 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_coherent, CTLFLAG_RD, &maps_coherent, 0,
157    "Number of active maps with BUS_DMA_COHERENT flag set");
158 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_total, CTLFLAG_RD,
159     &maploads_total, "Number of load operations performed");
160 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_bounced, CTLFLAG_RD,
161     &maploads_bounced, "Number of load operations that used bounce buffers");
162 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_coherent, CTLFLAG_RD,
163     &maploads_dmamem, "Number of load operations on BUS_DMA_COHERENT memory");
164 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_dmamem, CTLFLAG_RD,
165     &maploads_dmamem, "Number of load operations on bus_dmamem_alloc buffers");
166 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_mbuf, CTLFLAG_RD,
167     &maploads_mbuf, "Number of load operations for mbufs");
168 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_physmem, CTLFLAG_RD,
169     &maploads_physmem, "Number of load operations on physical buffers");
170 SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bpages, 0,
171    "Total bounce pages");
172
173 struct bus_dmamap {
174         struct bp_list          bpages;
175         int                     pagesneeded;
176         int                     pagesreserved;
177         bus_dma_tag_t           dmat;
178         struct memdesc          mem;
179         bus_dmamap_callback_t   *callback;
180         void                    *callback_arg;
181         int                     flags;
182 #define DMAMAP_COHERENT         (1 << 0)
183 #define DMAMAP_DMAMEM_ALLOC     (1 << 1)
184 #define DMAMAP_MBUF             (1 << 2)
185         STAILQ_ENTRY(bus_dmamap) links;
186         bus_dma_segment_t       *segments;
187         int                     sync_count;
188         struct sync_list        slist[];
189 };
190
191 static STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
192 static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist;
193
194 static void init_bounce_pages(void *dummy);
195 static int alloc_bounce_zone(bus_dma_tag_t dmat);
196 static int alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages);
197 static int reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
198     int commit);
199 static bus_addr_t add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map,
200     vm_offset_t vaddr, bus_addr_t addr, bus_size_t size);
201 static void free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage);
202 static void _bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap,
203     bus_dmamap_t map, void *buf, bus_size_t buflen, int flags);
204 static void _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map,
205     vm_paddr_t buf, bus_size_t buflen, int flags);
206 static int _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
207     int flags);
208 static void dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size);
209 static void dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op);
210
211 static busdma_bufalloc_t coherent_allocator;    /* Cache of coherent buffers */
212 static busdma_bufalloc_t standard_allocator;    /* Cache of standard buffers */
213
214 MALLOC_DEFINE(M_BUSDMA, "busdma", "busdma metadata");
215 MALLOC_DEFINE(M_BOUNCE, "bounce", "busdma bounce pages");
216
217 static void
218 busdma_init(void *dummy)
219 {
220         int uma_flags;
221
222         maploads_total    = counter_u64_alloc(M_WAITOK);
223         maploads_bounced  = counter_u64_alloc(M_WAITOK);
224         maploads_coherent = counter_u64_alloc(M_WAITOK);
225         maploads_dmamem   = counter_u64_alloc(M_WAITOK);
226         maploads_mbuf     = counter_u64_alloc(M_WAITOK);
227         maploads_physmem  = counter_u64_alloc(M_WAITOK);
228
229         uma_flags = 0;
230
231         /* Create a cache of buffers in standard (cacheable) memory. */
232         standard_allocator = busdma_bufalloc_create("buffer",
233             BUSDMA_DCACHE_ALIGN,/* minimum_alignment */
234             NULL,               /* uma_alloc func */
235             NULL,               /* uma_free func */
236             uma_flags);         /* uma_zcreate_flags */
237
238 #ifdef INVARIANTS
239         /*
240          * Force UMA zone to allocate service structures like
241          * slabs using own allocator. uma_debug code performs
242          * atomic ops on uma_slab_t fields and safety of this
243          * operation is not guaranteed for write-back caches
244          */
245         uma_flags = UMA_ZONE_OFFPAGE;
246 #endif
247         /*
248          * Create a cache of buffers in uncacheable memory, to implement the
249          * BUS_DMA_COHERENT (and potentially BUS_DMA_NOCACHE) flag.
250          */
251         coherent_allocator = busdma_bufalloc_create("coherent",
252             BUSDMA_DCACHE_ALIGN,/* minimum_alignment */
253             busdma_bufalloc_alloc_uncacheable,
254             busdma_bufalloc_free_uncacheable,
255             uma_flags); /* uma_zcreate_flags */
256 }
257
258 /*
259  * This init historically used SI_SUB_VM, but now the init code requires
260  * malloc(9) using M_BUSDMA memory and the pcpu zones for counter(9), which get
261  * set up by SI_SUB_KMEM and SI_ORDER_LAST, so we'll go right after that by
262  * using SI_SUB_KMEM+1.
263  */
264 SYSINIT(busdma, SI_SUB_KMEM+1, SI_ORDER_FIRST, busdma_init, NULL);
265
266 /*
267  * This routine checks the exclusion zone constraints from a tag against the
268  * physical RAM available on the machine.  If a tag specifies an exclusion zone
269  * but there's no RAM in that zone, then we avoid allocating resources to bounce
270  * a request, and we can use any memory allocator (as opposed to needing
271  * kmem_alloc_contig() just because it can allocate pages in an address range).
272  *
273  * Most tags have BUS_SPACE_MAXADDR or BUS_SPACE_MAXADDR_32BIT (they are the
274  * same value on 32-bit architectures) as their lowaddr constraint, and we can't
275  * possibly have RAM at an address higher than the highest address we can
276  * express, so we take a fast out.
277  */
278 static int
279 exclusion_bounce_check(vm_offset_t lowaddr, vm_offset_t highaddr)
280 {
281         int i;
282
283         if (lowaddr >= BUS_SPACE_MAXADDR)
284                 return (0);
285
286         for (i = 0; phys_avail[i] && phys_avail[i + 1]; i += 2) {
287                 if ((lowaddr >= phys_avail[i] && lowaddr < phys_avail[i + 1]) ||
288                     (lowaddr < phys_avail[i] && highaddr >= phys_avail[i]))
289                         return (1);
290         }
291         return (0);
292 }
293
294 /*
295  * Return true if the tag has an exclusion zone that could lead to bouncing.
296  */
297 static __inline int
298 exclusion_bounce(bus_dma_tag_t dmat)
299 {
300
301         return (dmat->flags & BUS_DMA_EXCL_BOUNCE);
302 }
303
304 /*
305  * Return true if the given address does not fall on the alignment boundary.
306  */
307 static __inline int
308 alignment_bounce(bus_dma_tag_t dmat, bus_addr_t addr)
309 {
310
311         return (addr & (dmat->alignment - 1));
312 }
313
314 /*
315  * Return true if the DMA should bounce because the start or end does not fall
316  * on a cacheline boundary (which would require a partial cacheline flush).
317  * COHERENT memory doesn't trigger cacheline flushes.  Memory allocated by
318  * bus_dmamem_alloc() is always aligned to cacheline boundaries, and there's a
319  * strict rule that such memory cannot be accessed by the CPU while DMA is in
320  * progress (or by multiple DMA engines at once), so that it's always safe to do
321  * full cacheline flushes even if that affects memory outside the range of a
322  * given DMA operation that doesn't involve the full allocated buffer.  If we're
323  * mapping an mbuf, that follows the same rules as a buffer we allocated.
324  */
325 static __inline int
326 cacheline_bounce(bus_dmamap_t map, bus_addr_t addr, bus_size_t size)
327 {
328
329         if (map->flags & (DMAMAP_DMAMEM_ALLOC | DMAMAP_COHERENT | DMAMAP_MBUF))
330                 return (0);
331         return ((addr | size) & BUSDMA_DCACHE_MASK);
332 }
333
334 /*
335  * Return true if we might need to bounce the DMA described by addr and size.
336  *
337  * This is used to quick-check whether we need to do the more expensive work of
338  * checking the DMA page-by-page looking for alignment and exclusion bounces.
339  *
340  * Note that the addr argument might be either virtual or physical.  It doesn't
341  * matter because we only look at the low-order bits, which are the same in both
342  * address spaces and maximum alignment of generic buffer is limited up to page
343  * size.
344  * Bouncing of buffers allocated by bus_dmamem_alloc()is not necessary, these
345  * always comply with the required rules (alignment, boundary, and address
346  * range).
347  */
348 static __inline int
349 might_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t addr,
350     bus_size_t size)
351 {
352
353         KASSERT(map->flags & DMAMAP_DMAMEM_ALLOC ||
354             dmat->alignment <= PAGE_SIZE,
355             ("%s: unsupported alignment (0x%08lx) for buffer not "
356             "allocated by bus_dmamem_alloc()",
357             __func__, dmat->alignment));
358
359         return (!(map->flags & DMAMAP_DMAMEM_ALLOC) &&
360             ((dmat->flags & BUS_DMA_EXCL_BOUNCE) ||
361             alignment_bounce(dmat, addr) ||
362             cacheline_bounce(map, addr, size)));
363 }
364
365 /*
366  * Return true if we must bounce the DMA described by paddr and size.
367  *
368  * Bouncing can be triggered by DMA that doesn't begin and end on cacheline
369  * boundaries, or doesn't begin on an alignment boundary, or falls within the
370  * exclusion zone of any tag in the ancestry chain.
371  *
372  * For exclusions, walk the chain of tags comparing paddr to the exclusion zone
373  * within each tag.  If the tag has a filter function, use it to decide whether
374  * the DMA needs to bounce, otherwise any DMA within the zone bounces.
375  */
376 static int
377 must_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t paddr,
378     bus_size_t size)
379 {
380
381         if (cacheline_bounce(map, paddr, size))
382                 return (1);
383
384         /*
385          *  The tag already contains ancestors' alignment restrictions so this
386          *  check doesn't need to be inside the loop.
387          */
388         if (alignment_bounce(dmat, paddr))
389                 return (1);
390
391         /*
392          * Even though each tag has an exclusion zone that is a superset of its
393          * own and all its ancestors' exclusions, the exclusion zone of each tag
394          * up the chain must be checked within the loop, because the busdma
395          * rules say the filter function is called only when the address lies
396          * within the low-highaddr range of the tag that filterfunc belongs to.
397          */
398         while (dmat != NULL && exclusion_bounce(dmat)) {
399                 if ((paddr >= dmat->lowaddr && paddr <= dmat->highaddr) &&
400                     (dmat->filter == NULL ||
401                     dmat->filter(dmat->filterarg, paddr) != 0))
402                         return (1);
403                 dmat = dmat->parent;
404         }
405
406         return (0);
407 }
408
409 /*
410  * Convenience function for manipulating driver locks from busdma (during
411  * busdma_swi, for example).  Drivers that don't provide their own locks
412  * should specify &Giant to dmat->lockfuncarg.  Drivers that use their own
413  * non-mutex locking scheme don't have to use this at all.
414  */
415 void
416 busdma_lock_mutex(void *arg, bus_dma_lock_op_t op)
417 {
418         struct mtx *dmtx;
419
420         dmtx = (struct mtx *)arg;
421         switch (op) {
422         case BUS_DMA_LOCK:
423                 mtx_lock(dmtx);
424                 break;
425         case BUS_DMA_UNLOCK:
426                 mtx_unlock(dmtx);
427                 break;
428         default:
429                 panic("Unknown operation 0x%x for busdma_lock_mutex!", op);
430         }
431 }
432
433 /*
434  * dflt_lock should never get called.  It gets put into the dma tag when
435  * lockfunc == NULL, which is only valid if the maps that are associated
436  * with the tag are meant to never be defered.
437  * XXX Should have a way to identify which driver is responsible here.
438  */
439 static void
440 dflt_lock(void *arg, bus_dma_lock_op_t op)
441 {
442
443         panic("driver error: busdma dflt_lock called");
444 }
445
446 /*
447  * Allocate a device specific dma_tag.
448  */
449 int
450 bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
451     bus_addr_t boundary, bus_addr_t lowaddr, bus_addr_t highaddr,
452     bus_dma_filter_t *filter, void *filterarg, bus_size_t maxsize,
453     int nsegments, bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
454     void *lockfuncarg, bus_dma_tag_t *dmat)
455 {
456         bus_dma_tag_t newtag;
457         int error = 0;
458
459         /* Basic sanity checking. */
460         KASSERT(boundary == 0 || powerof2(boundary),
461             ("dma tag boundary %lu, must be a power of 2", boundary));
462         KASSERT(boundary == 0 || boundary >= maxsegsz,
463             ("dma tag boundary %lu is < maxsegsz %lu\n", boundary, maxsegsz));
464         KASSERT(alignment != 0 && powerof2(alignment),
465             ("dma tag alignment %lu, must be non-zero power of 2", alignment));
466         KASSERT(maxsegsz != 0, ("dma tag maxsegsz must not be zero"));
467
468         /* Return a NULL tag on failure */
469         *dmat = NULL;
470
471         newtag = (bus_dma_tag_t)malloc(sizeof(*newtag), M_BUSDMA,
472             M_ZERO | M_NOWAIT);
473         if (newtag == NULL) {
474                 CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
475                     __func__, newtag, 0, error);
476                 return (ENOMEM);
477         }
478
479         newtag->parent = parent;
480         newtag->alignment = alignment;
481         newtag->boundary = boundary;
482         newtag->lowaddr = trunc_page((vm_paddr_t)lowaddr) + (PAGE_SIZE - 1);
483         newtag->highaddr = trunc_page((vm_paddr_t)highaddr) +
484             (PAGE_SIZE - 1);
485         newtag->filter = filter;
486         newtag->filterarg = filterarg;
487         newtag->maxsize = maxsize;
488         newtag->nsegments = nsegments;
489         newtag->maxsegsz = maxsegsz;
490         newtag->flags = flags;
491         newtag->ref_count = 1; /* Count ourself */
492         newtag->map_count = 0;
493         if (lockfunc != NULL) {
494                 newtag->lockfunc = lockfunc;
495                 newtag->lockfuncarg = lockfuncarg;
496         } else {
497                 newtag->lockfunc = dflt_lock;
498                 newtag->lockfuncarg = NULL;
499         }
500
501         /* Take into account any restrictions imposed by our parent tag */
502         if (parent != NULL) {
503                 newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
504                 newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
505                 newtag->alignment = MAX(parent->alignment, newtag->alignment);
506                 newtag->flags |= parent->flags & BUS_DMA_COULD_BOUNCE;
507                 newtag->flags |= parent->flags & BUS_DMA_COHERENT;
508                 if (newtag->boundary == 0)
509                         newtag->boundary = parent->boundary;
510                 else if (parent->boundary != 0)
511                         newtag->boundary = MIN(parent->boundary,
512                                                newtag->boundary);
513                 if (newtag->filter == NULL) {
514                         /*
515                          * Short circuit to looking at our parent directly
516                          * since we have encapsulated all of its information
517                          */
518                         newtag->filter = parent->filter;
519                         newtag->filterarg = parent->filterarg;
520                         newtag->parent = parent->parent;
521                 }
522                 if (newtag->parent != NULL)
523                         atomic_add_int(&parent->ref_count, 1);
524         }
525
526         if (exclusion_bounce_check(newtag->lowaddr, newtag->highaddr))
527                 newtag->flags |= BUS_DMA_EXCL_BOUNCE;
528         if (alignment_bounce(newtag, 1))
529                 newtag->flags |= BUS_DMA_ALIGN_BOUNCE;
530
531         /*
532          * Any request can auto-bounce due to cacheline alignment, in addition
533          * to any alignment or boundary specifications in the tag, so if the
534          * ALLOCNOW flag is set, there's always work to do.
535          */
536         if ((flags & BUS_DMA_ALLOCNOW) != 0) {
537                 struct bounce_zone *bz;
538                 /*
539                  * Round size up to a full page, and add one more page because
540                  * there can always be one more boundary crossing than the
541                  * number of pages in a transfer.
542                  */
543                 maxsize = roundup2(maxsize, PAGE_SIZE) + PAGE_SIZE;
544
545                 if ((error = alloc_bounce_zone(newtag)) != 0) {
546                         free(newtag, M_BUSDMA);
547                         return (error);
548                 }
549                 bz = newtag->bounce_zone;
550
551                 if (ptoa(bz->total_bpages) < maxsize) {
552                         int pages;
553
554                         pages = atop(maxsize) - bz->total_bpages;
555
556                         /* Add pages to our bounce pool */
557                         if (alloc_bounce_pages(newtag, pages) < pages)
558                                 error = ENOMEM;
559                 }
560                 /* Performed initial allocation */
561                 newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
562         } else
563                 newtag->bounce_zone = NULL;
564
565         if (error != 0) {
566                 free(newtag, M_BUSDMA);
567         } else {
568                 atomic_add_32(&tags_total, 1);
569                 *dmat = newtag;
570         }
571         CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
572             __func__, newtag, (newtag != NULL ? newtag->flags : 0), error);
573         return (error);
574 }
575
576 int
577 bus_dma_tag_set_domain(bus_dma_tag_t dmat, int domain)
578 {
579
580         return (0);
581 }
582
583 int
584 bus_dma_tag_destroy(bus_dma_tag_t dmat)
585 {
586         bus_dma_tag_t dmat_copy;
587         int error;
588
589         error = 0;
590         dmat_copy = dmat;
591
592         if (dmat != NULL) {
593
594                 if (dmat->map_count != 0) {
595                         error = EBUSY;
596                         goto out;
597                 }
598
599                 while (dmat != NULL) {
600                         bus_dma_tag_t parent;
601
602                         parent = dmat->parent;
603                         atomic_subtract_int(&dmat->ref_count, 1);
604                         if (dmat->ref_count == 0) {
605                                 atomic_subtract_32(&tags_total, 1);
606                                 free(dmat, M_BUSDMA);
607                                 /*
608                                  * Last reference count, so
609                                  * release our reference
610                                  * count on our parent.
611                                  */
612                                 dmat = parent;
613                         } else
614                                 dmat = NULL;
615                 }
616         }
617 out:
618         CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
619         return (error);
620 }
621
622 static int
623 allocate_bz_and_pages(bus_dma_tag_t dmat, bus_dmamap_t mapp)
624 {
625         struct bounce_zone *bz;
626         int maxpages;
627         int error;
628
629         if (dmat->bounce_zone == NULL)
630                 if ((error = alloc_bounce_zone(dmat)) != 0)
631                         return (error);
632         bz = dmat->bounce_zone;
633         /* Initialize the new map */
634         STAILQ_INIT(&(mapp->bpages));
635
636         /*
637          * Attempt to add pages to our pool on a per-instance basis up to a sane
638          * limit.  Even if the tag isn't flagged as COULD_BOUNCE due to
639          * alignment and boundary constraints, it could still auto-bounce due to
640          * cacheline alignment, which requires at most two bounce pages.
641          */
642         if (dmat->flags & BUS_DMA_COULD_BOUNCE)
643                 maxpages = MAX_BPAGES;
644         else
645                 maxpages = 2 * bz->map_count;
646         if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0 ||
647             (bz->map_count > 0 && bz->total_bpages < maxpages)) {
648                 int pages;
649
650                 pages = atop(roundup2(dmat->maxsize, PAGE_SIZE)) + 1;
651                 pages = MIN(maxpages - bz->total_bpages, pages);
652                 pages = MAX(pages, 2);
653                 if (alloc_bounce_pages(dmat, pages) < pages)
654                         return (ENOMEM);
655
656                 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0)
657                         dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
658         }
659         bz->map_count++;
660         return (0);
661 }
662
663 static bus_dmamap_t
664 allocate_map(bus_dma_tag_t dmat, int mflags)
665 {
666         int mapsize, segsize;
667         bus_dmamap_t map;
668
669         /*
670          * Allocate the map.  The map structure ends with an embedded
671          * variable-sized array of sync_list structures.  Following that
672          * we allocate enough extra space to hold the array of bus_dma_segments.
673          */
674         KASSERT(dmat->nsegments <= MAX_DMA_SEGMENTS,
675            ("cannot allocate %u dma segments (max is %u)",
676             dmat->nsegments, MAX_DMA_SEGMENTS));
677         segsize = sizeof(struct bus_dma_segment) * dmat->nsegments;
678         mapsize = sizeof(*map) + sizeof(struct sync_list) * dmat->nsegments;
679         map = malloc(mapsize + segsize, M_BUSDMA, mflags | M_ZERO);
680         if (map == NULL) {
681                 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
682                 return (NULL);
683         }
684         map->segments = (bus_dma_segment_t *)((uintptr_t)map + mapsize);
685         return (map);
686 }
687
688 /*
689  * Allocate a handle for mapping from kva/uva/physical
690  * address space into bus device space.
691  */
692 int
693 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
694 {
695         bus_dmamap_t map;
696         int error = 0;
697
698         *mapp = map = allocate_map(dmat, M_NOWAIT);
699         if (map == NULL) {
700                 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
701                 return (ENOMEM);
702         }
703
704         /*
705          * Bouncing might be required if the driver asks for an exclusion
706          * region, a data alignment that is stricter than 1, or DMA that begins
707          * or ends with a partial cacheline.  Whether bouncing will actually
708          * happen can't be known until mapping time, but we need to pre-allocate
709          * resources now because we might not be allowed to at mapping time.
710          */
711         error = allocate_bz_and_pages(dmat, map);
712         if (error != 0) {
713                 free(map, M_BUSDMA);
714                 *mapp = NULL;
715                 return (error);
716         }
717         if (map->flags & DMAMAP_COHERENT)
718                 atomic_add_32(&maps_coherent, 1);
719         atomic_add_32(&maps_total, 1);
720         dmat->map_count++;
721
722         return (0);
723 }
724
725 /*
726  * Destroy a handle for mapping from kva/uva/physical
727  * address space into bus device space.
728  */
729 int
730 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
731 {
732
733         if (STAILQ_FIRST(&map->bpages) != NULL || map->sync_count != 0) {
734                 CTR3(KTR_BUSDMA, "%s: tag %p error %d",
735                     __func__, dmat, EBUSY);
736                 return (EBUSY);
737         }
738         if (dmat->bounce_zone)
739                 dmat->bounce_zone->map_count--;
740         if (map->flags & DMAMAP_COHERENT)
741                 atomic_subtract_32(&maps_coherent, 1);
742         atomic_subtract_32(&maps_total, 1);
743         free(map, M_BUSDMA);
744         dmat->map_count--;
745         CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
746         return (0);
747 }
748
749 /*
750  * Allocate a piece of memory that can be efficiently mapped into bus device
751  * space based on the constraints listed in the dma tag.  Returns a pointer to
752  * the allocated memory, and a pointer to an associated bus_dmamap.
753  */
754 int
755 bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
756     bus_dmamap_t *mapp)
757 {
758         busdma_bufalloc_t ba;
759         struct busdma_bufzone *bufzone;
760         bus_dmamap_t map;
761         vm_memattr_t memattr;
762         int mflags;
763
764         if (flags & BUS_DMA_NOWAIT)
765                 mflags = M_NOWAIT;
766         else
767                 mflags = M_WAITOK;
768         if (flags & BUS_DMA_ZERO)
769                 mflags |= M_ZERO;
770
771         *mapp = map = allocate_map(dmat, mflags);
772         if (map == NULL) {
773                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
774                     __func__, dmat, dmat->flags, ENOMEM);
775                 return (ENOMEM);
776         }
777         map->flags = DMAMAP_DMAMEM_ALLOC;
778
779         /* For coherent memory, set the map flag that disables sync ops. */
780         if (flags & BUS_DMA_COHERENT)
781                 map->flags |= DMAMAP_COHERENT;
782
783         /*
784          * Choose a busdma buffer allocator based on memory type flags.
785          * If the tag's COHERENT flag is set, that means normal memory
786          * is already coherent, use the normal allocator.
787          */
788         if ((flags & BUS_DMA_COHERENT) &&
789             ((dmat->flags & BUS_DMA_COHERENT) == 0)) {
790                 memattr = VM_MEMATTR_UNCACHEABLE;
791                 ba = coherent_allocator;
792         } else {
793                 memattr = VM_MEMATTR_DEFAULT;
794                 ba = standard_allocator;
795         }
796
797         /*
798          * Try to find a bufzone in the allocator that holds a cache of buffers
799          * of the right size for this request.  If the buffer is too big to be
800          * held in the allocator cache, this returns NULL.
801          */
802         bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
803
804         /*
805          * Allocate the buffer from the uma(9) allocator if...
806          *  - It's small enough to be in the allocator (bufzone not NULL).
807          *  - The alignment constraint isn't larger than the allocation size
808          *    (the allocator aligns buffers to their size boundaries).
809          *  - There's no need to handle lowaddr/highaddr exclusion zones.
810          * else allocate non-contiguous pages if...
811          *  - The page count that could get allocated doesn't exceed
812          *    nsegments also when the maximum segment size is less
813          *    than PAGE_SIZE.
814          *  - The alignment constraint isn't larger than a page boundary.
815          *  - There are no boundary-crossing constraints.
816          * else allocate a block of contiguous pages because one or more of the
817          * constraints is something that only the contig allocator can fulfill.
818          */
819         if (bufzone != NULL && dmat->alignment <= bufzone->size &&
820             !exclusion_bounce(dmat)) {
821                 *vaddr = uma_zalloc(bufzone->umazone, mflags);
822         } else if (dmat->nsegments >=
823             howmany(dmat->maxsize, MIN(dmat->maxsegsz, PAGE_SIZE)) &&
824             dmat->alignment <= PAGE_SIZE &&
825             (dmat->boundary % PAGE_SIZE) == 0) {
826                 *vaddr = (void *)kmem_alloc_attr(dmat->maxsize, mflags, 0,
827                     dmat->lowaddr, memattr);
828         } else {
829                 *vaddr = (void *)kmem_alloc_contig(dmat->maxsize, mflags, 0,
830                     dmat->lowaddr, dmat->alignment, dmat->boundary, memattr);
831         }
832         if (*vaddr == NULL) {
833                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
834                     __func__, dmat, dmat->flags, ENOMEM);
835                 free(map, M_BUSDMA);
836                 *mapp = NULL;
837                 return (ENOMEM);
838         }
839         if (map->flags & DMAMAP_COHERENT)
840                 atomic_add_32(&maps_coherent, 1);
841         atomic_add_32(&maps_dmamem, 1);
842         atomic_add_32(&maps_total, 1);
843         dmat->map_count++;
844
845         CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
846             __func__, dmat, dmat->flags, 0);
847         return (0);
848 }
849
850 /*
851  * Free a piece of memory that was allocated via bus_dmamem_alloc, along with
852  * its associated map.
853  */
854 void
855 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
856 {
857         struct busdma_bufzone *bufzone;
858         busdma_bufalloc_t ba;
859
860         if ((map->flags & DMAMAP_COHERENT) &&
861             ((dmat->flags & BUS_DMA_COHERENT) == 0))
862                 ba = coherent_allocator;
863         else
864                 ba = standard_allocator;
865
866         bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
867
868         if (bufzone != NULL && dmat->alignment <= bufzone->size &&
869             !exclusion_bounce(dmat))
870                 uma_zfree(bufzone->umazone, vaddr);
871         else
872                 kmem_free((vm_offset_t)vaddr, dmat->maxsize);
873
874         dmat->map_count--;
875         if (map->flags & DMAMAP_COHERENT)
876                 atomic_subtract_32(&maps_coherent, 1);
877         atomic_subtract_32(&maps_total, 1);
878         atomic_subtract_32(&maps_dmamem, 1);
879         free(map, M_BUSDMA);
880         CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat, dmat->flags);
881 }
882
883 static void
884 _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
885     bus_size_t buflen, int flags)
886 {
887         bus_addr_t curaddr;
888         bus_size_t sgsize;
889
890         if (map->pagesneeded == 0) {
891                 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
892                     " map= %p, pagesneeded= %d",
893                     dmat->lowaddr, dmat->boundary, dmat->alignment,
894                     map, map->pagesneeded);
895                 /*
896                  * Count the number of bounce pages
897                  * needed in order to complete this transfer
898                  */
899                 curaddr = buf;
900                 while (buflen != 0) {
901                         sgsize = MIN(buflen, dmat->maxsegsz);
902                         if (must_bounce(dmat, map, curaddr, sgsize) != 0) {
903                                 sgsize = MIN(sgsize,
904                                     PAGE_SIZE - (curaddr & PAGE_MASK));
905                                 map->pagesneeded++;
906                         }
907                         curaddr += sgsize;
908                         buflen -= sgsize;
909                 }
910                 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
911         }
912 }
913
914 static void
915 _bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap, bus_dmamap_t map,
916     void *buf, bus_size_t buflen, int flags)
917 {
918         vm_offset_t vaddr;
919         vm_offset_t vendaddr;
920         bus_addr_t paddr;
921
922         if (map->pagesneeded == 0) {
923                 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
924                     " map= %p, pagesneeded= %d",
925                     dmat->lowaddr, dmat->boundary, dmat->alignment,
926                     map, map->pagesneeded);
927                 /*
928                  * Count the number of bounce pages
929                  * needed in order to complete this transfer
930                  */
931                 vaddr = (vm_offset_t)buf;
932                 vendaddr = (vm_offset_t)buf + buflen;
933
934                 while (vaddr < vendaddr) {
935                         if (__predict_true(pmap == kernel_pmap))
936                                 paddr = pmap_kextract(vaddr);
937                         else
938                                 paddr = pmap_extract(pmap, vaddr);
939                         if (must_bounce(dmat, map, paddr,
940                             min(vendaddr - vaddr, (PAGE_SIZE - ((vm_offset_t)vaddr &
941                             PAGE_MASK)))) != 0) {
942                                 map->pagesneeded++;
943                         }
944                         vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
945
946                 }
947                 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
948         }
949 }
950
951 static int
952 _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int flags)
953 {
954
955         /* Reserve Necessary Bounce Pages */
956         mtx_lock(&bounce_lock);
957         if (flags & BUS_DMA_NOWAIT) {
958                 if (reserve_bounce_pages(dmat, map, 0) != 0) {
959                         map->pagesneeded = 0;
960                         mtx_unlock(&bounce_lock);
961                         return (ENOMEM);
962                 }
963         } else {
964                 if (reserve_bounce_pages(dmat, map, 1) != 0) {
965                         /* Queue us for resources */
966                         STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
967                         mtx_unlock(&bounce_lock);
968                         return (EINPROGRESS);
969                 }
970         }
971         mtx_unlock(&bounce_lock);
972
973         return (0);
974 }
975
976 /*
977  * Add a single contiguous physical range to the segment list.
978  */
979 static int
980 _bus_dmamap_addseg(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t curaddr,
981     bus_size_t sgsize, bus_dma_segment_t *segs, int *segp)
982 {
983         bus_addr_t baddr, bmask;
984         int seg;
985
986         /*
987          * Make sure we don't cross any boundaries.
988          */
989         bmask = ~(dmat->boundary - 1);
990         if (dmat->boundary > 0) {
991                 baddr = (curaddr + dmat->boundary) & bmask;
992                 if (sgsize > (baddr - curaddr))
993                         sgsize = (baddr - curaddr);
994         }
995
996         /*
997          * Insert chunk into a segment, coalescing with
998          * previous segment if possible.
999          */
1000         seg = *segp;
1001         if (seg == -1) {
1002                 seg = 0;
1003                 segs[seg].ds_addr = curaddr;
1004                 segs[seg].ds_len = sgsize;
1005         } else {
1006                 if (curaddr == segs[seg].ds_addr + segs[seg].ds_len &&
1007                     (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
1008                     (dmat->boundary == 0 ||
1009                     (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
1010                         segs[seg].ds_len += sgsize;
1011                 else {
1012                         if (++seg >= dmat->nsegments)
1013                                 return (0);
1014                         segs[seg].ds_addr = curaddr;
1015                         segs[seg].ds_len = sgsize;
1016                 }
1017         }
1018         *segp = seg;
1019         return (sgsize);
1020 }
1021
1022 /*
1023  * Utility function to load a physical buffer.  segp contains
1024  * the starting segment on entrace, and the ending segment on exit.
1025  */
1026 int
1027 _bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
1028     bus_size_t buflen, int flags, bus_dma_segment_t *segs, int *segp)
1029 {
1030         bus_addr_t curaddr;
1031         bus_addr_t sl_end = 0;
1032         bus_size_t sgsize;
1033         struct sync_list *sl;
1034         int error;
1035
1036         if (segs == NULL)
1037                 segs = map->segments;
1038
1039         counter_u64_add(maploads_total, 1);
1040         counter_u64_add(maploads_physmem, 1);
1041
1042         if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1043                 _bus_dmamap_count_phys(dmat, map, buf, buflen, flags);
1044                 if (map->pagesneeded != 0) {
1045                         counter_u64_add(maploads_bounced, 1);
1046                         error = _bus_dmamap_reserve_pages(dmat, map, flags);
1047                         if (error)
1048                                 return (error);
1049                 }
1050         }
1051
1052         sl = map->slist + map->sync_count - 1;
1053
1054         while (buflen > 0) {
1055                 curaddr = buf;
1056                 sgsize = MIN(buflen, dmat->maxsegsz);
1057                 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1058                     sgsize)) {
1059                         sgsize = MIN(sgsize, PAGE_SIZE - (curaddr & PAGE_MASK));
1060                         curaddr = add_bounce_page(dmat, map, 0, curaddr,
1061                             sgsize);
1062                 } else if ((dmat->flags & BUS_DMA_COHERENT) == 0) {
1063                         if (map->sync_count > 0)
1064                                 sl_end = sl->paddr + sl->datacount;
1065
1066                         if (map->sync_count == 0 || curaddr != sl_end) {
1067                                 if (++map->sync_count > dmat->nsegments)
1068                                         break;
1069                                 sl++;
1070                                 sl->vaddr = 0;
1071                                 sl->paddr = curaddr;
1072                                 sl->datacount = sgsize;
1073                                 sl->pages = PHYS_TO_VM_PAGE(curaddr);
1074                                 KASSERT(sl->pages != NULL,
1075                                     ("%s: page at PA:0x%08lx is not in "
1076                                     "vm_page_array", __func__, curaddr));
1077                         } else
1078                                 sl->datacount += sgsize;
1079                 }
1080                 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1081                     segp);
1082                 if (sgsize == 0)
1083                         break;
1084                 buf += sgsize;
1085                 buflen -= sgsize;
1086         }
1087
1088         /*
1089          * Did we fit?
1090          */
1091         if (buflen != 0) {
1092                 bus_dmamap_unload(dmat, map);
1093                 return (EFBIG); /* XXX better return value here? */
1094         }
1095         return (0);
1096 }
1097
1098 int
1099 _bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map,
1100     struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
1101     bus_dma_segment_t *segs, int *segp)
1102 {
1103
1104         return (bus_dmamap_load_ma_triv(dmat, map, ma, tlen, ma_offs, flags,
1105             segs, segp));
1106 }
1107
1108 /*
1109  * Utility function to load a linear buffer.  segp contains
1110  * the starting segment on entrance, and the ending segment on exit.
1111  */
1112 int
1113 _bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
1114     bus_size_t buflen, pmap_t pmap, int flags, bus_dma_segment_t *segs,
1115     int *segp)
1116 {
1117         bus_size_t sgsize;
1118         bus_addr_t curaddr;
1119         bus_addr_t sl_pend = 0;
1120         vm_offset_t kvaddr, vaddr, sl_vend = 0;
1121         struct sync_list *sl;
1122         int error;
1123
1124         counter_u64_add(maploads_total, 1);
1125         if (map->flags & DMAMAP_COHERENT)
1126                 counter_u64_add(maploads_coherent, 1);
1127         if (map->flags & DMAMAP_DMAMEM_ALLOC)
1128                 counter_u64_add(maploads_dmamem, 1);
1129
1130         if (segs == NULL)
1131                 segs = map->segments;
1132
1133         if (flags & BUS_DMA_LOAD_MBUF) {
1134                 counter_u64_add(maploads_mbuf, 1);
1135                 map->flags |= DMAMAP_MBUF;
1136         }
1137
1138         if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1139                 _bus_dmamap_count_pages(dmat, pmap, map, buf, buflen, flags);
1140                 if (map->pagesneeded != 0) {
1141                         counter_u64_add(maploads_bounced, 1);
1142                         error = _bus_dmamap_reserve_pages(dmat, map, flags);
1143                         if (error)
1144                                 return (error);
1145                 }
1146         }
1147
1148         sl = map->slist + map->sync_count - 1;
1149         vaddr = (vm_offset_t)buf;
1150
1151         while (buflen > 0) {
1152                 /*
1153                  * Get the physical address for this segment.
1154                  */
1155                 if (__predict_true(pmap == kernel_pmap)) {
1156                         curaddr = pmap_kextract(vaddr);
1157                         kvaddr = vaddr;
1158                 } else {
1159                         curaddr = pmap_extract(pmap, vaddr);
1160                         kvaddr = 0;
1161                 }
1162
1163                 /*
1164                  * Compute the segment size, and adjust counts.
1165                  */
1166                 sgsize = PAGE_SIZE - (curaddr & PAGE_MASK);
1167                 if (sgsize > dmat->maxsegsz)
1168                         sgsize = dmat->maxsegsz;
1169                 if (buflen < sgsize)
1170                         sgsize = buflen;
1171
1172                 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1173                     sgsize)) {
1174                         curaddr = add_bounce_page(dmat, map, kvaddr, curaddr,
1175                             sgsize);
1176                 } else if ((dmat->flags & BUS_DMA_COHERENT) == 0) {
1177                         if (map->sync_count > 0) {
1178                                 sl_pend = sl->paddr + sl->datacount;
1179                                 sl_vend = sl->vaddr + sl->datacount;
1180                         }
1181
1182                         if (map->sync_count == 0 ||
1183                             (kvaddr != 0 && kvaddr != sl_vend) ||
1184                             (curaddr != sl_pend)) {
1185
1186                                 if (++map->sync_count > dmat->nsegments)
1187                                         goto cleanup;
1188                                 sl++;
1189                                 sl->vaddr = kvaddr;
1190                                 sl->paddr = curaddr;
1191                                 if (kvaddr != 0) {
1192                                         sl->pages = NULL;
1193                                 } else {
1194                                         sl->pages = PHYS_TO_VM_PAGE(curaddr);
1195                                         KASSERT(sl->pages != NULL,
1196                                             ("%s: page at PA:0x%08lx is not "
1197                                             "in vm_page_array", __func__,
1198                                             curaddr));
1199                                 }
1200                                 sl->datacount = sgsize;
1201                         } else
1202                                 sl->datacount += sgsize;
1203                 }
1204                 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1205                     segp);
1206                 if (sgsize == 0)
1207                         break;
1208                 vaddr += sgsize;
1209                 buflen -= sgsize;
1210         }
1211
1212 cleanup:
1213         /*
1214          * Did we fit?
1215          */
1216         if (buflen != 0) {
1217                 bus_dmamap_unload(dmat, map);
1218                 return (EFBIG); /* XXX better return value here? */
1219         }
1220         return (0);
1221 }
1222
1223 void
1224 _bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map, struct memdesc *mem,
1225     bus_dmamap_callback_t *callback, void *callback_arg)
1226 {
1227
1228         map->mem = *mem;
1229         map->dmat = dmat;
1230         map->callback = callback;
1231         map->callback_arg = callback_arg;
1232 }
1233
1234 bus_dma_segment_t *
1235 _bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map,
1236     bus_dma_segment_t *segs, int nsegs, int error)
1237 {
1238
1239         if (segs == NULL)
1240                 segs = map->segments;
1241         return (segs);
1242 }
1243
1244 /*
1245  * Release the mapping held by map.
1246  */
1247 void
1248 bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1249 {
1250         struct bounce_page *bpage;
1251         struct bounce_zone *bz;
1252
1253         if ((bz = dmat->bounce_zone) != NULL) {
1254                 while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1255                         STAILQ_REMOVE_HEAD(&map->bpages, links);
1256                         free_bounce_page(dmat, bpage);
1257                 }
1258
1259                 bz = dmat->bounce_zone;
1260                 bz->free_bpages += map->pagesreserved;
1261                 bz->reserved_bpages -= map->pagesreserved;
1262                 map->pagesreserved = 0;
1263                 map->pagesneeded = 0;
1264         }
1265         map->sync_count = 0;
1266         map->flags &= ~DMAMAP_MBUF;
1267 }
1268
1269 static void
1270 dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size)
1271 {
1272         /*
1273          * Write back any partial cachelines immediately before and
1274          * after the DMA region.  We don't need to round the address
1275          * down to the nearest cacheline or specify the exact size,
1276          * as dcache_wb_poc() will do the rounding for us and works
1277          * at cacheline granularity.
1278          */
1279         if (va & BUSDMA_DCACHE_MASK)
1280                 dcache_wb_poc(va, pa, 1);
1281         if ((va + size) & BUSDMA_DCACHE_MASK)
1282                 dcache_wb_poc(va + size, pa + size, 1);
1283
1284         dcache_inv_poc_dma(va, pa, size);
1285 }
1286
1287 static void
1288 dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op)
1289 {
1290         uint32_t len, offset;
1291         vm_page_t m;
1292         vm_paddr_t pa;
1293         vm_offset_t va, tempva;
1294         bus_size_t size;
1295
1296         offset = sl->paddr & PAGE_MASK;
1297         m = sl->pages;
1298         size = sl->datacount;
1299         pa = sl->paddr;
1300
1301         for ( ; size != 0; size -= len, pa += len, offset = 0, ++m) {
1302                 tempva = 0;
1303                 if (sl->vaddr == 0) {
1304                         len = min(PAGE_SIZE - offset, size);
1305                         tempva = pmap_quick_enter_page(m);
1306                         va = tempva | offset;
1307                         KASSERT(pa == (VM_PAGE_TO_PHYS(m) | offset),
1308                             ("unexpected vm_page_t phys: 0x%08x != 0x%08x",
1309                             VM_PAGE_TO_PHYS(m) | offset, pa));
1310                 } else {
1311                         len = sl->datacount;
1312                         va = sl->vaddr;
1313                 }
1314
1315                 switch (op) {
1316                 case BUS_DMASYNC_PREWRITE:
1317                 case BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD:
1318                         dcache_wb_poc(va, pa, len);
1319                         break;
1320                 case BUS_DMASYNC_PREREAD:
1321                         /*
1322                          * An mbuf may start in the middle of a cacheline. There
1323                          * will be no cpu writes to the beginning of that line
1324                          * (which contains the mbuf header) while dma is in
1325                          * progress.  Handle that case by doing a writeback of
1326                          * just the first cacheline before invalidating the
1327                          * overall buffer.  Any mbuf in a chain may have this
1328                          * misalignment.  Buffers which are not mbufs bounce if
1329                          * they are not aligned to a cacheline.
1330                          */
1331                         dma_preread_safe(va, pa, len);
1332                         break;
1333                 case BUS_DMASYNC_POSTREAD:
1334                 case BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE:
1335                         dcache_inv_poc(va, pa, len);
1336                         break;
1337                 default:
1338                         panic("unsupported combination of sync operations: "
1339                               "0x%08x\n", op);
1340                 }
1341
1342                 if (tempva != 0)
1343                         pmap_quick_remove_page(tempva);
1344         }
1345 }
1346
1347 void
1348 bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1349 {
1350         struct bounce_page *bpage;
1351         struct sync_list *sl, *end;
1352         vm_offset_t datavaddr, tempvaddr;
1353
1354         if (op == BUS_DMASYNC_POSTWRITE)
1355                 return;
1356
1357         /*
1358          * If the buffer was from user space, it is possible that this is not
1359          * the same vm map, especially on a POST operation.  It's not clear that
1360          * dma on userland buffers can work at all right now.  To be safe, until
1361          * we're able to test direct userland dma, panic on a map mismatch.
1362          */
1363         if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1364
1365                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1366                     "performing bounce", __func__, dmat, dmat->flags, op);
1367
1368                 /*
1369                  * For PREWRITE do a writeback.  Clean the caches from the
1370                  * innermost to the outermost levels.
1371                  */
1372                 if (op & BUS_DMASYNC_PREWRITE) {
1373                         while (bpage != NULL) {
1374                                 tempvaddr = 0;
1375                                 datavaddr = bpage->datavaddr;
1376                                 if (datavaddr == 0) {
1377                                         tempvaddr = pmap_quick_enter_page(
1378                                             bpage->datapage);
1379                                         datavaddr = tempvaddr | bpage->dataoffs;
1380                                 }
1381                                 bcopy((void *)datavaddr, (void *)bpage->vaddr,
1382                                     bpage->datacount);
1383                                 if (tempvaddr != 0)
1384                                         pmap_quick_remove_page(tempvaddr);
1385                                 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1386                                         dcache_wb_poc(bpage->vaddr,
1387                                             bpage->busaddr, bpage->datacount);
1388                                 bpage = STAILQ_NEXT(bpage, links);
1389                         }
1390                         dmat->bounce_zone->total_bounced++;
1391                 }
1392
1393                 /*
1394                  * Do an invalidate for PREREAD unless a writeback was already
1395                  * done above due to PREWRITE also being set.  The reason for a
1396                  * PREREAD invalidate is to prevent dirty lines currently in the
1397                  * cache from being evicted during the DMA.  If a writeback was
1398                  * done due to PREWRITE also being set there will be no dirty
1399                  * lines and the POSTREAD invalidate handles the rest. The
1400                  * invalidate is done from the innermost to outermost level. If
1401                  * L2 were done first, a dirty cacheline could be automatically
1402                  * evicted from L1 before we invalidated it, re-dirtying the L2.
1403                  */
1404                 if ((op & BUS_DMASYNC_PREREAD) && !(op & BUS_DMASYNC_PREWRITE)) {
1405                         bpage = STAILQ_FIRST(&map->bpages);
1406                         while (bpage != NULL) {
1407                                 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1408                                         dcache_inv_poc_dma(bpage->vaddr,
1409                                             bpage->busaddr, bpage->datacount);
1410                                 bpage = STAILQ_NEXT(bpage, links);
1411                         }
1412                 }
1413
1414                 /*
1415                  * Re-invalidate the caches on a POSTREAD, even though they were
1416                  * already invalidated at PREREAD time.  Aggressive prefetching
1417                  * due to accesses to other data near the dma buffer could have
1418                  * brought buffer data into the caches which is now stale.  The
1419                  * caches are invalidated from the outermost to innermost; the
1420                  * prefetches could be happening right now, and if L1 were
1421                  * invalidated first, stale L2 data could be prefetched into L1.
1422                  */
1423                 if (op & BUS_DMASYNC_POSTREAD) {
1424                         while (bpage != NULL) {
1425                                 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1426                                         dcache_inv_poc(bpage->vaddr,
1427                                             bpage->busaddr, bpage->datacount);
1428                                 tempvaddr = 0;
1429                                 datavaddr = bpage->datavaddr;
1430                                 if (datavaddr == 0) {
1431                                         tempvaddr = pmap_quick_enter_page(
1432                                             bpage->datapage);
1433                                         datavaddr = tempvaddr | bpage->dataoffs;
1434                                 }
1435                                 bcopy((void *)bpage->vaddr, (void *)datavaddr,
1436                                     bpage->datacount);
1437                                 if (tempvaddr != 0)
1438                                         pmap_quick_remove_page(tempvaddr);
1439                                 bpage = STAILQ_NEXT(bpage, links);
1440                         }
1441                         dmat->bounce_zone->total_bounced++;
1442                 }
1443         }
1444
1445         /*
1446          * For COHERENT memory no cache maintenance is necessary, but ensure all
1447          * writes have reached memory for the PREWRITE case.  No action is
1448          * needed for a PREREAD without PREWRITE also set, because that would
1449          * imply that the cpu had written to the COHERENT buffer and expected
1450          * the dma device to see that change, and by definition a PREWRITE sync
1451          * is required to make that happen.
1452          */
1453         if (map->flags & DMAMAP_COHERENT) {
1454                 if (op & BUS_DMASYNC_PREWRITE) {
1455                         dsb();
1456                         if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1457                                 cpu_l2cache_drain_writebuf();
1458                 }
1459                 return;
1460         }
1461
1462         /*
1463          * Cache maintenance for normal (non-COHERENT non-bounce) buffers.  All
1464          * the comments about the sequences for flushing cache levels in the
1465          * bounce buffer code above apply here as well.  In particular, the fact
1466          * that the sequence is inner-to-outer for PREREAD invalidation and
1467          * outer-to-inner for POSTREAD invalidation is not a mistake.
1468          */
1469         if (map->sync_count != 0) {
1470                 sl = &map->slist[0];
1471                 end = &map->slist[map->sync_count];
1472                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1473                     "performing sync", __func__, dmat, dmat->flags, op);
1474
1475                 for ( ; sl != end; ++sl)
1476                         dma_dcache_sync(sl, op);
1477         }
1478 }
1479
1480 static void
1481 init_bounce_pages(void *dummy __unused)
1482 {
1483
1484         total_bpages = 0;
1485         STAILQ_INIT(&bounce_zone_list);
1486         STAILQ_INIT(&bounce_map_waitinglist);
1487         STAILQ_INIT(&bounce_map_callbacklist);
1488         mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
1489 }
1490 SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
1491
1492 static struct sysctl_ctx_list *
1493 busdma_sysctl_tree(struct bounce_zone *bz)
1494 {
1495
1496         return (&bz->sysctl_tree);
1497 }
1498
1499 static struct sysctl_oid *
1500 busdma_sysctl_tree_top(struct bounce_zone *bz)
1501 {
1502
1503         return (bz->sysctl_tree_top);
1504 }
1505
1506 static int
1507 alloc_bounce_zone(bus_dma_tag_t dmat)
1508 {
1509         struct bounce_zone *bz;
1510
1511         /* Check to see if we already have a suitable zone */
1512         STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1513                 if ((dmat->alignment <= bz->alignment) &&
1514                     (dmat->lowaddr >= bz->lowaddr)) {
1515                         dmat->bounce_zone = bz;
1516                         return (0);
1517                 }
1518         }
1519
1520         if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_BUSDMA,
1521             M_NOWAIT | M_ZERO)) == NULL)
1522                 return (ENOMEM);
1523
1524         STAILQ_INIT(&bz->bounce_page_list);
1525         bz->free_bpages = 0;
1526         bz->reserved_bpages = 0;
1527         bz->active_bpages = 0;
1528         bz->lowaddr = dmat->lowaddr;
1529         bz->alignment = MAX(dmat->alignment, PAGE_SIZE);
1530         bz->map_count = 0;
1531         snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1532         busdma_zonecount++;
1533         snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1534         STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1535         dmat->bounce_zone = bz;
1536
1537         sysctl_ctx_init(&bz->sysctl_tree);
1538         bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
1539             SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1540             CTLFLAG_RD, 0, "");
1541         if (bz->sysctl_tree_top == NULL) {
1542                 sysctl_ctx_free(&bz->sysctl_tree);
1543                 return (0);     /* XXX error code? */
1544         }
1545
1546         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1547             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1548             "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1549             "Total bounce pages");
1550         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1551             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1552             "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1553             "Free bounce pages");
1554         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1555             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1556             "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1557             "Reserved bounce pages");
1558         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1559             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1560             "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1561             "Active bounce pages");
1562         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1563             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1564             "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1565             "Total bounce requests (pages bounced)");
1566         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1567             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1568             "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1569             "Total bounce requests that were deferred");
1570         SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1571             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1572             "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1573         SYSCTL_ADD_ULONG(busdma_sysctl_tree(bz),
1574             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1575             "alignment", CTLFLAG_RD, &bz->alignment, "");
1576
1577         return (0);
1578 }
1579
1580 static int
1581 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1582 {
1583         struct bounce_zone *bz;
1584         int count;
1585
1586         bz = dmat->bounce_zone;
1587         count = 0;
1588         while (numpages > 0) {
1589                 struct bounce_page *bpage;
1590
1591                 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_BUSDMA,
1592                     M_NOWAIT | M_ZERO);
1593
1594                 if (bpage == NULL)
1595                         break;
1596                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_BOUNCE,
1597                     M_NOWAIT, 0ul, bz->lowaddr, PAGE_SIZE, 0);
1598                 if (bpage->vaddr == 0) {
1599                         free(bpage, M_BUSDMA);
1600                         break;
1601                 }
1602                 bpage->busaddr = pmap_kextract(bpage->vaddr);
1603                 mtx_lock(&bounce_lock);
1604                 STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1605                 total_bpages++;
1606                 bz->total_bpages++;
1607                 bz->free_bpages++;
1608                 mtx_unlock(&bounce_lock);
1609                 count++;
1610                 numpages--;
1611         }
1612         return (count);
1613 }
1614
1615 static int
1616 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1617 {
1618         struct bounce_zone *bz;
1619         int pages;
1620
1621         mtx_assert(&bounce_lock, MA_OWNED);
1622         bz = dmat->bounce_zone;
1623         pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1624         if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1625                 return (map->pagesneeded - (map->pagesreserved + pages));
1626         bz->free_bpages -= pages;
1627         bz->reserved_bpages += pages;
1628         map->pagesreserved += pages;
1629         pages = map->pagesneeded - map->pagesreserved;
1630
1631         return (pages);
1632 }
1633
1634 static bus_addr_t
1635 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1636     bus_addr_t addr, bus_size_t size)
1637 {
1638         struct bounce_zone *bz;
1639         struct bounce_page *bpage;
1640
1641         KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1642         KASSERT(map != NULL, ("add_bounce_page: bad map %p", map));
1643
1644         bz = dmat->bounce_zone;
1645         if (map->pagesneeded == 0)
1646                 panic("add_bounce_page: map doesn't need any pages");
1647         map->pagesneeded--;
1648
1649         if (map->pagesreserved == 0)
1650                 panic("add_bounce_page: map doesn't need any pages");
1651         map->pagesreserved--;
1652
1653         mtx_lock(&bounce_lock);
1654         bpage = STAILQ_FIRST(&bz->bounce_page_list);
1655         if (bpage == NULL)
1656                 panic("add_bounce_page: free page list is empty");
1657
1658         STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1659         bz->reserved_bpages--;
1660         bz->active_bpages++;
1661         mtx_unlock(&bounce_lock);
1662
1663         if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1664                 /* Page offset needs to be preserved. */
1665                 bpage->vaddr |= addr & PAGE_MASK;
1666                 bpage->busaddr |= addr & PAGE_MASK;
1667         }
1668         bpage->datavaddr = vaddr;
1669         bpage->datapage = PHYS_TO_VM_PAGE(addr);
1670         bpage->dataoffs = addr & PAGE_MASK;
1671         bpage->datacount = size;
1672         STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1673         return (bpage->busaddr);
1674 }
1675
1676 static void
1677 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1678 {
1679         struct bus_dmamap *map;
1680         struct bounce_zone *bz;
1681
1682         bz = dmat->bounce_zone;
1683         bpage->datavaddr = 0;
1684         bpage->datacount = 0;
1685         if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1686                 /*
1687                  * Reset the bounce page to start at offset 0.  Other uses
1688                  * of this bounce page may need to store a full page of
1689                  * data and/or assume it starts on a page boundary.
1690                  */
1691                 bpage->vaddr &= ~PAGE_MASK;
1692                 bpage->busaddr &= ~PAGE_MASK;
1693         }
1694
1695         mtx_lock(&bounce_lock);
1696         STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1697         bz->free_bpages++;
1698         bz->active_bpages--;
1699         if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1700                 if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1701                         STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1702                         STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1703                             map, links);
1704                         busdma_swi_pending = 1;
1705                         bz->total_deferred++;
1706                         swi_sched(vm_ih, 0);
1707                 }
1708         }
1709         mtx_unlock(&bounce_lock);
1710 }
1711
1712 void
1713 busdma_swi(void)
1714 {
1715         bus_dma_tag_t dmat;
1716         struct bus_dmamap *map;
1717
1718         mtx_lock(&bounce_lock);
1719         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1720                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1721                 mtx_unlock(&bounce_lock);
1722                 dmat = map->dmat;
1723                 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_LOCK);
1724                 bus_dmamap_load_mem(map->dmat, map, &map->mem, map->callback,
1725                     map->callback_arg, BUS_DMA_WAITOK);
1726                 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_UNLOCK);
1727                 mtx_lock(&bounce_lock);
1728         }
1729         mtx_unlock(&bounce_lock);
1730 }