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