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