xref: /freebsd/sys/arm/arm/busdma_machdep.c (revision e17f5b1d)
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_init(bus_dma_tag_template_t *t, bus_dma_tag_t parent)
581 {
582 
583 	if (t == NULL)
584 		return;
585 
586 	t->parent = parent;
587 	t->alignment = 1;
588 	t->boundary = 0;
589 	t->lowaddr = t->highaddr = BUS_SPACE_MAXADDR;
590 	t->maxsize = t->maxsegsize = BUS_SPACE_MAXSIZE;
591 	t->nsegments = BUS_SPACE_UNRESTRICTED;
592 	t->lockfunc = NULL;
593 	t->lockfuncarg = NULL;
594 	t->flags = 0;
595 }
596 
597 int
598 bus_dma_template_tag(bus_dma_tag_template_t *t, bus_dma_tag_t *dmat)
599 {
600 
601 	if (t == NULL || dmat == NULL)
602 		return (EINVAL);
603 
604 	return (bus_dma_tag_create(t->parent, t->alignment, t->boundary,
605 	    t->lowaddr, t->highaddr, NULL, NULL, t->maxsize,
606 	    t->nsegments, t->maxsegsize, t->flags, t->lockfunc, t->lockfuncarg,
607 	    dmat));
608 }
609 
610 void
611 bus_dma_template_clone(bus_dma_tag_template_t *t, bus_dma_tag_t dmat)
612 {
613 
614 	if (t == NULL || dmat == NULL)
615 		return;
616 
617 	t->parent = dmat->parent;
618 	t->alignment = dmat->alignment;
619 	t->boundary = dmat->boundary;
620 	t->lowaddr = dmat->lowaddr;
621 	t->highaddr = dmat->highaddr;
622 	t->maxsize = dmat->maxsize;
623 	t->nsegments = dmat->nsegments;
624 	t->maxsegsize = dmat->maxsegsz;
625 	t->flags = dmat->flags;
626 	t->lockfunc = dmat->lockfunc;
627 	t->lockfuncarg = dmat->lockfuncarg;
628 }
629 
630 int
631 bus_dma_tag_set_domain(bus_dma_tag_t dmat, int domain)
632 {
633 
634 	return (0);
635 }
636 
637 int
638 bus_dma_tag_destroy(bus_dma_tag_t dmat)
639 {
640 	bus_dma_tag_t dmat_copy;
641 	int error;
642 
643 	error = 0;
644 	dmat_copy = dmat;
645 
646 	if (dmat != NULL) {
647 
648 		if (dmat->map_count != 0) {
649 			error = EBUSY;
650 			goto out;
651 		}
652 
653 		while (dmat != NULL) {
654 			bus_dma_tag_t parent;
655 
656 			parent = dmat->parent;
657 			atomic_subtract_int(&dmat->ref_count, 1);
658 			if (dmat->ref_count == 0) {
659 				atomic_subtract_32(&tags_total, 1);
660 				free(dmat, M_BUSDMA);
661 				/*
662 				 * Last reference count, so
663 				 * release our reference
664 				 * count on our parent.
665 				 */
666 				dmat = parent;
667 			} else
668 				dmat = NULL;
669 		}
670 	}
671 out:
672 	CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
673 	return (error);
674 }
675 
676 static int
677 allocate_bz_and_pages(bus_dma_tag_t dmat, bus_dmamap_t mapp)
678 {
679 	struct bounce_zone *bz;
680 	int maxpages;
681 	int error;
682 
683 	if (dmat->bounce_zone == NULL)
684 		if ((error = alloc_bounce_zone(dmat)) != 0)
685 			return (error);
686 	bz = dmat->bounce_zone;
687 	/* Initialize the new map */
688 	STAILQ_INIT(&(mapp->bpages));
689 
690 	/*
691 	 * Attempt to add pages to our pool on a per-instance basis up to a sane
692 	 * limit.  Even if the tag isn't flagged as COULD_BOUNCE due to
693 	 * alignment and boundary constraints, it could still auto-bounce due to
694 	 * cacheline alignment, which requires at most two bounce pages.
695 	 */
696 	if (dmat->flags & BUS_DMA_COULD_BOUNCE)
697 		maxpages = MAX_BPAGES;
698 	else
699 		maxpages = 2 * bz->map_count;
700 	if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0 ||
701 	    (bz->map_count > 0 && bz->total_bpages < maxpages)) {
702 		int pages;
703 
704 		pages = atop(roundup2(dmat->maxsize, PAGE_SIZE)) + 1;
705 		pages = MIN(maxpages - bz->total_bpages, pages);
706 		pages = MAX(pages, 2);
707 		if (alloc_bounce_pages(dmat, pages) < pages)
708 			return (ENOMEM);
709 
710 		if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0)
711 			dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
712 	}
713 	bz->map_count++;
714 	return (0);
715 }
716 
717 static bus_dmamap_t
718 allocate_map(bus_dma_tag_t dmat, int mflags)
719 {
720 	int mapsize, segsize;
721 	bus_dmamap_t map;
722 
723 	/*
724 	 * Allocate the map.  The map structure ends with an embedded
725 	 * variable-sized array of sync_list structures.  Following that
726 	 * we allocate enough extra space to hold the array of bus_dma_segments.
727 	 */
728 	KASSERT(dmat->nsegments <= MAX_DMA_SEGMENTS,
729 	   ("cannot allocate %u dma segments (max is %u)",
730 	    dmat->nsegments, MAX_DMA_SEGMENTS));
731 	segsize = sizeof(struct bus_dma_segment) * dmat->nsegments;
732 	mapsize = sizeof(*map) + sizeof(struct sync_list) * dmat->nsegments;
733 	map = malloc(mapsize + segsize, M_BUSDMA, mflags | M_ZERO);
734 	if (map == NULL) {
735 		CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
736 		return (NULL);
737 	}
738 	map->segments = (bus_dma_segment_t *)((uintptr_t)map + mapsize);
739 	STAILQ_INIT(&map->bpages);
740 	return (map);
741 }
742 
743 /*
744  * Allocate a handle for mapping from kva/uva/physical
745  * address space into bus device space.
746  */
747 int
748 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
749 {
750 	bus_dmamap_t map;
751 	int error = 0;
752 
753 	*mapp = map = allocate_map(dmat, M_NOWAIT);
754 	if (map == NULL) {
755 		CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
756 		return (ENOMEM);
757 	}
758 
759 	/*
760 	 * Bouncing might be required if the driver asks for an exclusion
761 	 * region, a data alignment that is stricter than 1, or DMA that begins
762 	 * or ends with a partial cacheline.  Whether bouncing will actually
763 	 * happen can't be known until mapping time, but we need to pre-allocate
764 	 * resources now because we might not be allowed to at mapping time.
765 	 */
766 	error = allocate_bz_and_pages(dmat, map);
767 	if (error != 0) {
768 		free(map, M_BUSDMA);
769 		*mapp = NULL;
770 		return (error);
771 	}
772 	if (map->flags & DMAMAP_COHERENT)
773 		atomic_add_32(&maps_coherent, 1);
774 	atomic_add_32(&maps_total, 1);
775 	dmat->map_count++;
776 
777 	return (0);
778 }
779 
780 /*
781  * Destroy a handle for mapping from kva/uva/physical
782  * address space into bus device space.
783  */
784 int
785 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
786 {
787 
788 	if (STAILQ_FIRST(&map->bpages) != NULL || map->sync_count != 0) {
789 		CTR3(KTR_BUSDMA, "%s: tag %p error %d",
790 		    __func__, dmat, EBUSY);
791 		return (EBUSY);
792 	}
793 	if (dmat->bounce_zone)
794 		dmat->bounce_zone->map_count--;
795 	if (map->flags & DMAMAP_COHERENT)
796 		atomic_subtract_32(&maps_coherent, 1);
797 	atomic_subtract_32(&maps_total, 1);
798 	free(map, M_BUSDMA);
799 	dmat->map_count--;
800 	CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
801 	return (0);
802 }
803 
804 /*
805  * Allocate a piece of memory that can be efficiently mapped into bus device
806  * space based on the constraints listed in the dma tag.  Returns a pointer to
807  * the allocated memory, and a pointer to an associated bus_dmamap.
808  */
809 int
810 bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
811     bus_dmamap_t *mapp)
812 {
813 	busdma_bufalloc_t ba;
814 	struct busdma_bufzone *bufzone;
815 	bus_dmamap_t map;
816 	vm_memattr_t memattr;
817 	int mflags;
818 
819 	if (flags & BUS_DMA_NOWAIT)
820 		mflags = M_NOWAIT;
821 	else
822 		mflags = M_WAITOK;
823 	if (flags & BUS_DMA_ZERO)
824 		mflags |= M_ZERO;
825 
826 	*mapp = map = allocate_map(dmat, mflags);
827 	if (map == NULL) {
828 		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
829 		    __func__, dmat, dmat->flags, ENOMEM);
830 		return (ENOMEM);
831 	}
832 	map->flags = DMAMAP_DMAMEM_ALLOC;
833 
834 	/* For coherent memory, set the map flag that disables sync ops. */
835 	if (flags & BUS_DMA_COHERENT)
836 		map->flags |= DMAMAP_COHERENT;
837 
838 	/*
839 	 * Choose a busdma buffer allocator based on memory type flags.
840 	 * If the tag's COHERENT flag is set, that means normal memory
841 	 * is already coherent, use the normal allocator.
842 	 */
843 	if ((flags & BUS_DMA_COHERENT) &&
844 	    ((dmat->flags & BUS_DMA_COHERENT) == 0)) {
845 		memattr = VM_MEMATTR_UNCACHEABLE;
846 		ba = coherent_allocator;
847 	} else {
848 		memattr = VM_MEMATTR_DEFAULT;
849 		ba = standard_allocator;
850 	}
851 
852 	/*
853 	 * Try to find a bufzone in the allocator that holds a cache of buffers
854 	 * of the right size for this request.  If the buffer is too big to be
855 	 * held in the allocator cache, this returns NULL.
856 	 */
857 	bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
858 
859 	/*
860 	 * Allocate the buffer from the uma(9) allocator if...
861 	 *  - It's small enough to be in the allocator (bufzone not NULL).
862 	 *  - The alignment constraint isn't larger than the allocation size
863 	 *    (the allocator aligns buffers to their size boundaries).
864 	 *  - There's no need to handle lowaddr/highaddr exclusion zones.
865 	 * else allocate non-contiguous pages if...
866 	 *  - The page count that could get allocated doesn't exceed
867 	 *    nsegments also when the maximum segment size is less
868 	 *    than PAGE_SIZE.
869 	 *  - The alignment constraint isn't larger than a page boundary.
870 	 *  - There are no boundary-crossing constraints.
871 	 * else allocate a block of contiguous pages because one or more of the
872 	 * constraints is something that only the contig allocator can fulfill.
873 	 */
874 	if (bufzone != NULL && dmat->alignment <= bufzone->size &&
875 	    !exclusion_bounce(dmat)) {
876 		*vaddr = uma_zalloc(bufzone->umazone, mflags);
877 	} else if (dmat->nsegments >=
878 	    howmany(dmat->maxsize, MIN(dmat->maxsegsz, PAGE_SIZE)) &&
879 	    dmat->alignment <= PAGE_SIZE &&
880 	    (dmat->boundary % PAGE_SIZE) == 0) {
881 		*vaddr = (void *)kmem_alloc_attr(dmat->maxsize, mflags, 0,
882 		    dmat->lowaddr, memattr);
883 	} else {
884 		*vaddr = (void *)kmem_alloc_contig(dmat->maxsize, mflags, 0,
885 		    dmat->lowaddr, dmat->alignment, dmat->boundary, memattr);
886 	}
887 	if (*vaddr == NULL) {
888 		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
889 		    __func__, dmat, dmat->flags, ENOMEM);
890 		free(map, M_BUSDMA);
891 		*mapp = NULL;
892 		return (ENOMEM);
893 	}
894 	if (map->flags & DMAMAP_COHERENT)
895 		atomic_add_32(&maps_coherent, 1);
896 	atomic_add_32(&maps_dmamem, 1);
897 	atomic_add_32(&maps_total, 1);
898 	dmat->map_count++;
899 
900 	CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
901 	    __func__, dmat, dmat->flags, 0);
902 	return (0);
903 }
904 
905 /*
906  * Free a piece of memory that was allocated via bus_dmamem_alloc, along with
907  * its associated map.
908  */
909 void
910 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
911 {
912 	struct busdma_bufzone *bufzone;
913 	busdma_bufalloc_t ba;
914 
915 	if ((map->flags & DMAMAP_COHERENT) &&
916 	    ((dmat->flags & BUS_DMA_COHERENT) == 0))
917 		ba = coherent_allocator;
918 	else
919 		ba = standard_allocator;
920 
921 	bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
922 
923 	if (bufzone != NULL && dmat->alignment <= bufzone->size &&
924 	    !exclusion_bounce(dmat))
925 		uma_zfree(bufzone->umazone, vaddr);
926 	else
927 		kmem_free((vm_offset_t)vaddr, dmat->maxsize);
928 
929 	dmat->map_count--;
930 	if (map->flags & DMAMAP_COHERENT)
931 		atomic_subtract_32(&maps_coherent, 1);
932 	atomic_subtract_32(&maps_total, 1);
933 	atomic_subtract_32(&maps_dmamem, 1);
934 	free(map, M_BUSDMA);
935 	CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat, dmat->flags);
936 }
937 
938 static void
939 _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
940     bus_size_t buflen, int flags)
941 {
942 	bus_addr_t curaddr;
943 	bus_size_t sgsize;
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 		curaddr = buf;
955 		while (buflen != 0) {
956 			sgsize = MIN(buflen, dmat->maxsegsz);
957 			if (must_bounce(dmat, map, curaddr, sgsize) != 0) {
958 				sgsize = MIN(sgsize,
959 				    PAGE_SIZE - (curaddr & PAGE_MASK));
960 				map->pagesneeded++;
961 			}
962 			curaddr += sgsize;
963 			buflen -= sgsize;
964 		}
965 		CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
966 	}
967 }
968 
969 static void
970 _bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap, bus_dmamap_t map,
971     void *buf, bus_size_t buflen, int flags)
972 {
973 	vm_offset_t vaddr;
974 	vm_offset_t vendaddr;
975 	bus_addr_t paddr;
976 
977 	if (map->pagesneeded == 0) {
978 		CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
979 		    " map= %p, pagesneeded= %d",
980 		    dmat->lowaddr, dmat->boundary, dmat->alignment,
981 		    map, map->pagesneeded);
982 		/*
983 		 * Count the number of bounce pages
984 		 * needed in order to complete this transfer
985 		 */
986 		vaddr = (vm_offset_t)buf;
987 		vendaddr = (vm_offset_t)buf + buflen;
988 
989 		while (vaddr < vendaddr) {
990 			if (__predict_true(pmap == kernel_pmap))
991 				paddr = pmap_kextract(vaddr);
992 			else
993 				paddr = pmap_extract(pmap, vaddr);
994 			if (must_bounce(dmat, map, paddr,
995 			    min(vendaddr - vaddr, (PAGE_SIZE - ((vm_offset_t)vaddr &
996 			    PAGE_MASK)))) != 0) {
997 				map->pagesneeded++;
998 			}
999 			vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
1000 
1001 		}
1002 		CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
1003 	}
1004 }
1005 
1006 static int
1007 _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int flags)
1008 {
1009 
1010 	/* Reserve Necessary Bounce Pages */
1011 	mtx_lock(&bounce_lock);
1012 	if (flags & BUS_DMA_NOWAIT) {
1013 		if (reserve_bounce_pages(dmat, map, 0) != 0) {
1014 			map->pagesneeded = 0;
1015 			mtx_unlock(&bounce_lock);
1016 			return (ENOMEM);
1017 		}
1018 	} else {
1019 		if (reserve_bounce_pages(dmat, map, 1) != 0) {
1020 			/* Queue us for resources */
1021 			STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
1022 			mtx_unlock(&bounce_lock);
1023 			return (EINPROGRESS);
1024 		}
1025 	}
1026 	mtx_unlock(&bounce_lock);
1027 
1028 	return (0);
1029 }
1030 
1031 /*
1032  * Add a single contiguous physical range to the segment list.
1033  */
1034 static int
1035 _bus_dmamap_addseg(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t curaddr,
1036     bus_size_t sgsize, bus_dma_segment_t *segs, int *segp)
1037 {
1038 	bus_addr_t baddr, bmask;
1039 	int seg;
1040 
1041 	/*
1042 	 * Make sure we don't cross any boundaries.
1043 	 */
1044 	bmask = ~(dmat->boundary - 1);
1045 	if (dmat->boundary > 0) {
1046 		baddr = (curaddr + dmat->boundary) & bmask;
1047 		if (sgsize > (baddr - curaddr))
1048 			sgsize = (baddr - curaddr);
1049 	}
1050 
1051 	/*
1052 	 * Insert chunk into a segment, coalescing with
1053 	 * previous segment if possible.
1054 	 */
1055 	seg = *segp;
1056 	if (seg == -1) {
1057 		seg = 0;
1058 		segs[seg].ds_addr = curaddr;
1059 		segs[seg].ds_len = sgsize;
1060 	} else {
1061 		if (curaddr == segs[seg].ds_addr + segs[seg].ds_len &&
1062 		    (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
1063 		    (dmat->boundary == 0 ||
1064 		    (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
1065 			segs[seg].ds_len += sgsize;
1066 		else {
1067 			if (++seg >= dmat->nsegments)
1068 				return (0);
1069 			segs[seg].ds_addr = curaddr;
1070 			segs[seg].ds_len = sgsize;
1071 		}
1072 	}
1073 	*segp = seg;
1074 	return (sgsize);
1075 }
1076 
1077 /*
1078  * Utility function to load a physical buffer.  segp contains
1079  * the starting segment on entrace, and the ending segment on exit.
1080  */
1081 int
1082 _bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
1083     bus_size_t buflen, int flags, bus_dma_segment_t *segs, int *segp)
1084 {
1085 	bus_addr_t curaddr;
1086 	bus_addr_t sl_end = 0;
1087 	bus_size_t sgsize;
1088 	struct sync_list *sl;
1089 	int error;
1090 
1091 	if (segs == NULL)
1092 		segs = map->segments;
1093 
1094 	counter_u64_add(maploads_total, 1);
1095 	counter_u64_add(maploads_physmem, 1);
1096 
1097 	if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1098 		_bus_dmamap_count_phys(dmat, map, buf, buflen, flags);
1099 		if (map->pagesneeded != 0) {
1100 			counter_u64_add(maploads_bounced, 1);
1101 			error = _bus_dmamap_reserve_pages(dmat, map, flags);
1102 			if (error)
1103 				return (error);
1104 		}
1105 	}
1106 
1107 	sl = map->slist + map->sync_count - 1;
1108 
1109 	while (buflen > 0) {
1110 		curaddr = buf;
1111 		sgsize = MIN(buflen, dmat->maxsegsz);
1112 		if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1113 		    sgsize)) {
1114 			sgsize = MIN(sgsize, PAGE_SIZE - (curaddr & PAGE_MASK));
1115 			curaddr = add_bounce_page(dmat, map, 0, curaddr,
1116 			    sgsize);
1117 		} else if ((dmat->flags & BUS_DMA_COHERENT) == 0) {
1118 			if (map->sync_count > 0)
1119 				sl_end = sl->paddr + sl->datacount;
1120 
1121 			if (map->sync_count == 0 || curaddr != sl_end) {
1122 				if (++map->sync_count > dmat->nsegments)
1123 					break;
1124 				sl++;
1125 				sl->vaddr = 0;
1126 				sl->paddr = curaddr;
1127 				sl->datacount = sgsize;
1128 				sl->pages = PHYS_TO_VM_PAGE(curaddr);
1129 				KASSERT(sl->pages != NULL,
1130 				    ("%s: page at PA:0x%08lx is not in "
1131 				    "vm_page_array", __func__, curaddr));
1132 			} else
1133 				sl->datacount += sgsize;
1134 		}
1135 		sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1136 		    segp);
1137 		if (sgsize == 0)
1138 			break;
1139 		buf += sgsize;
1140 		buflen -= sgsize;
1141 	}
1142 
1143 	/*
1144 	 * Did we fit?
1145 	 */
1146 	if (buflen != 0) {
1147 		bus_dmamap_unload(dmat, map);
1148 		return (EFBIG); /* XXX better return value here? */
1149 	}
1150 	return (0);
1151 }
1152 
1153 int
1154 _bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map,
1155     struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
1156     bus_dma_segment_t *segs, int *segp)
1157 {
1158 
1159 	return (bus_dmamap_load_ma_triv(dmat, map, ma, tlen, ma_offs, flags,
1160 	    segs, segp));
1161 }
1162 
1163 /*
1164  * Utility function to load a linear buffer.  segp contains
1165  * the starting segment on entrance, and the ending segment on exit.
1166  */
1167 int
1168 _bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
1169     bus_size_t buflen, pmap_t pmap, int flags, bus_dma_segment_t *segs,
1170     int *segp)
1171 {
1172 	bus_size_t sgsize;
1173 	bus_addr_t curaddr;
1174 	bus_addr_t sl_pend = 0;
1175 	vm_offset_t kvaddr, vaddr, sl_vend = 0;
1176 	struct sync_list *sl;
1177 	int error;
1178 
1179 	counter_u64_add(maploads_total, 1);
1180 	if (map->flags & DMAMAP_COHERENT)
1181 		counter_u64_add(maploads_coherent, 1);
1182 	if (map->flags & DMAMAP_DMAMEM_ALLOC)
1183 		counter_u64_add(maploads_dmamem, 1);
1184 
1185 	if (segs == NULL)
1186 		segs = map->segments;
1187 
1188 	if (flags & BUS_DMA_LOAD_MBUF) {
1189 		counter_u64_add(maploads_mbuf, 1);
1190 		map->flags |= DMAMAP_MBUF;
1191 	}
1192 
1193 	if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1194 		_bus_dmamap_count_pages(dmat, pmap, map, buf, buflen, flags);
1195 		if (map->pagesneeded != 0) {
1196 			counter_u64_add(maploads_bounced, 1);
1197 			error = _bus_dmamap_reserve_pages(dmat, map, flags);
1198 			if (error)
1199 				return (error);
1200 		}
1201 	}
1202 
1203 	sl = map->slist + map->sync_count - 1;
1204 	vaddr = (vm_offset_t)buf;
1205 
1206 	while (buflen > 0) {
1207 		/*
1208 		 * Get the physical address for this segment.
1209 		 */
1210 		if (__predict_true(pmap == kernel_pmap)) {
1211 			curaddr = pmap_kextract(vaddr);
1212 			kvaddr = vaddr;
1213 		} else {
1214 			curaddr = pmap_extract(pmap, vaddr);
1215 			kvaddr = 0;
1216 		}
1217 
1218 		/*
1219 		 * Compute the segment size, and adjust counts.
1220 		 */
1221 		sgsize = PAGE_SIZE - (curaddr & PAGE_MASK);
1222 		if (sgsize > dmat->maxsegsz)
1223 			sgsize = dmat->maxsegsz;
1224 		if (buflen < sgsize)
1225 			sgsize = buflen;
1226 
1227 		if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1228 		    sgsize)) {
1229 			curaddr = add_bounce_page(dmat, map, kvaddr, curaddr,
1230 			    sgsize);
1231 		} else if ((dmat->flags & BUS_DMA_COHERENT) == 0) {
1232 			if (map->sync_count > 0) {
1233 				sl_pend = sl->paddr + sl->datacount;
1234 				sl_vend = sl->vaddr + sl->datacount;
1235 			}
1236 
1237 			if (map->sync_count == 0 ||
1238 			    (kvaddr != 0 && kvaddr != sl_vend) ||
1239 			    (curaddr != sl_pend)) {
1240 
1241 				if (++map->sync_count > dmat->nsegments)
1242 					goto cleanup;
1243 				sl++;
1244 				sl->vaddr = kvaddr;
1245 				sl->paddr = curaddr;
1246 				if (kvaddr != 0) {
1247 					sl->pages = NULL;
1248 				} else {
1249 					sl->pages = PHYS_TO_VM_PAGE(curaddr);
1250 					KASSERT(sl->pages != NULL,
1251 					    ("%s: page at PA:0x%08lx is not "
1252 					    "in vm_page_array", __func__,
1253 					    curaddr));
1254 				}
1255 				sl->datacount = sgsize;
1256 			} else
1257 				sl->datacount += sgsize;
1258 		}
1259 		sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1260 		    segp);
1261 		if (sgsize == 0)
1262 			break;
1263 		vaddr += sgsize;
1264 		buflen -= sgsize;
1265 	}
1266 
1267 cleanup:
1268 	/*
1269 	 * Did we fit?
1270 	 */
1271 	if (buflen != 0) {
1272 		bus_dmamap_unload(dmat, map);
1273 		return (EFBIG); /* XXX better return value here? */
1274 	}
1275 	return (0);
1276 }
1277 
1278 void
1279 _bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map, struct memdesc *mem,
1280     bus_dmamap_callback_t *callback, void *callback_arg)
1281 {
1282 
1283 	map->mem = *mem;
1284 	map->dmat = dmat;
1285 	map->callback = callback;
1286 	map->callback_arg = callback_arg;
1287 }
1288 
1289 bus_dma_segment_t *
1290 _bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map,
1291     bus_dma_segment_t *segs, int nsegs, int error)
1292 {
1293 
1294 	if (segs == NULL)
1295 		segs = map->segments;
1296 	return (segs);
1297 }
1298 
1299 /*
1300  * Release the mapping held by map.
1301  */
1302 void
1303 bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1304 {
1305 	struct bounce_page *bpage;
1306 	struct bounce_zone *bz;
1307 
1308 	if ((bz = dmat->bounce_zone) != NULL) {
1309 		while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1310 			STAILQ_REMOVE_HEAD(&map->bpages, links);
1311 			free_bounce_page(dmat, bpage);
1312 		}
1313 
1314 		bz = dmat->bounce_zone;
1315 		bz->free_bpages += map->pagesreserved;
1316 		bz->reserved_bpages -= map->pagesreserved;
1317 		map->pagesreserved = 0;
1318 		map->pagesneeded = 0;
1319 	}
1320 	map->sync_count = 0;
1321 	map->flags &= ~DMAMAP_MBUF;
1322 }
1323 
1324 static void
1325 dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size)
1326 {
1327 	/*
1328 	 * Write back any partial cachelines immediately before and
1329 	 * after the DMA region.  We don't need to round the address
1330 	 * down to the nearest cacheline or specify the exact size,
1331 	 * as dcache_wb_poc() will do the rounding for us and works
1332 	 * at cacheline granularity.
1333 	 */
1334 	if (va & BUSDMA_DCACHE_MASK)
1335 		dcache_wb_poc(va, pa, 1);
1336 	if ((va + size) & BUSDMA_DCACHE_MASK)
1337 		dcache_wb_poc(va + size, pa + size, 1);
1338 
1339 	dcache_inv_poc_dma(va, pa, size);
1340 }
1341 
1342 static void
1343 dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op)
1344 {
1345 	uint32_t len, offset;
1346 	vm_page_t m;
1347 	vm_paddr_t pa;
1348 	vm_offset_t va, tempva;
1349 	bus_size_t size;
1350 
1351 	offset = sl->paddr & PAGE_MASK;
1352 	m = sl->pages;
1353 	size = sl->datacount;
1354 	pa = sl->paddr;
1355 
1356 	for ( ; size != 0; size -= len, pa += len, offset = 0, ++m) {
1357 		tempva = 0;
1358 		if (sl->vaddr == 0) {
1359 			len = min(PAGE_SIZE - offset, size);
1360 			tempva = pmap_quick_enter_page(m);
1361 			va = tempva | offset;
1362 			KASSERT(pa == (VM_PAGE_TO_PHYS(m) | offset),
1363 			    ("unexpected vm_page_t phys: 0x%08x != 0x%08x",
1364 			    VM_PAGE_TO_PHYS(m) | offset, pa));
1365 		} else {
1366 			len = sl->datacount;
1367 			va = sl->vaddr;
1368 		}
1369 
1370 		switch (op) {
1371 		case BUS_DMASYNC_PREWRITE:
1372 		case BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD:
1373 			dcache_wb_poc(va, pa, len);
1374 			break;
1375 		case BUS_DMASYNC_PREREAD:
1376 			/*
1377 			 * An mbuf may start in the middle of a cacheline. There
1378 			 * will be no cpu writes to the beginning of that line
1379 			 * (which contains the mbuf header) while dma is in
1380 			 * progress.  Handle that case by doing a writeback of
1381 			 * just the first cacheline before invalidating the
1382 			 * overall buffer.  Any mbuf in a chain may have this
1383 			 * misalignment.  Buffers which are not mbufs bounce if
1384 			 * they are not aligned to a cacheline.
1385 			 */
1386 			dma_preread_safe(va, pa, len);
1387 			break;
1388 		case BUS_DMASYNC_POSTREAD:
1389 		case BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE:
1390 			dcache_inv_poc(va, pa, len);
1391 			break;
1392 		default:
1393 			panic("unsupported combination of sync operations: "
1394                               "0x%08x\n", op);
1395 		}
1396 
1397 		if (tempva != 0)
1398 			pmap_quick_remove_page(tempva);
1399 	}
1400 }
1401 
1402 void
1403 bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1404 {
1405 	struct bounce_page *bpage;
1406 	struct sync_list *sl, *end;
1407 	vm_offset_t datavaddr, tempvaddr;
1408 
1409 	if (op == BUS_DMASYNC_POSTWRITE)
1410 		return;
1411 
1412 	/*
1413 	 * If the buffer was from user space, it is possible that this is not
1414 	 * the same vm map, especially on a POST operation.  It's not clear that
1415 	 * dma on userland buffers can work at all right now.  To be safe, until
1416 	 * we're able to test direct userland dma, panic on a map mismatch.
1417 	 */
1418 	if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1419 
1420 		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1421 		    "performing bounce", __func__, dmat, dmat->flags, op);
1422 
1423 		/*
1424 		 * For PREWRITE do a writeback.  Clean the caches from the
1425 		 * innermost to the outermost levels.
1426 		 */
1427 		if (op & BUS_DMASYNC_PREWRITE) {
1428 			while (bpage != NULL) {
1429 				tempvaddr = 0;
1430 				datavaddr = bpage->datavaddr;
1431 				if (datavaddr == 0) {
1432 					tempvaddr = pmap_quick_enter_page(
1433 					    bpage->datapage);
1434 					datavaddr = tempvaddr | bpage->dataoffs;
1435 				}
1436 				bcopy((void *)datavaddr, (void *)bpage->vaddr,
1437 				    bpage->datacount);
1438 				if (tempvaddr != 0)
1439 					pmap_quick_remove_page(tempvaddr);
1440 				if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1441 					dcache_wb_poc(bpage->vaddr,
1442 					    bpage->busaddr, bpage->datacount);
1443 				bpage = STAILQ_NEXT(bpage, links);
1444 			}
1445 			dmat->bounce_zone->total_bounced++;
1446 		}
1447 
1448 		/*
1449 		 * Do an invalidate for PREREAD unless a writeback was already
1450 		 * done above due to PREWRITE also being set.  The reason for a
1451 		 * PREREAD invalidate is to prevent dirty lines currently in the
1452 		 * cache from being evicted during the DMA.  If a writeback was
1453 		 * done due to PREWRITE also being set there will be no dirty
1454 		 * lines and the POSTREAD invalidate handles the rest. The
1455 		 * invalidate is done from the innermost to outermost level. If
1456 		 * L2 were done first, a dirty cacheline could be automatically
1457 		 * evicted from L1 before we invalidated it, re-dirtying the L2.
1458 		 */
1459 		if ((op & BUS_DMASYNC_PREREAD) && !(op & BUS_DMASYNC_PREWRITE)) {
1460 			bpage = STAILQ_FIRST(&map->bpages);
1461 			while (bpage != NULL) {
1462 				if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1463 					dcache_inv_poc_dma(bpage->vaddr,
1464 					    bpage->busaddr, bpage->datacount);
1465 				bpage = STAILQ_NEXT(bpage, links);
1466 			}
1467 		}
1468 
1469 		/*
1470 		 * Re-invalidate the caches on a POSTREAD, even though they were
1471 		 * already invalidated at PREREAD time.  Aggressive prefetching
1472 		 * due to accesses to other data near the dma buffer could have
1473 		 * brought buffer data into the caches which is now stale.  The
1474 		 * caches are invalidated from the outermost to innermost; the
1475 		 * prefetches could be happening right now, and if L1 were
1476 		 * invalidated first, stale L2 data could be prefetched into L1.
1477 		 */
1478 		if (op & BUS_DMASYNC_POSTREAD) {
1479 			while (bpage != NULL) {
1480 				if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1481 					dcache_inv_poc(bpage->vaddr,
1482 					    bpage->busaddr, bpage->datacount);
1483 				tempvaddr = 0;
1484 				datavaddr = bpage->datavaddr;
1485 				if (datavaddr == 0) {
1486 					tempvaddr = pmap_quick_enter_page(
1487 					    bpage->datapage);
1488 					datavaddr = tempvaddr | bpage->dataoffs;
1489 				}
1490 				bcopy((void *)bpage->vaddr, (void *)datavaddr,
1491 				    bpage->datacount);
1492 				if (tempvaddr != 0)
1493 					pmap_quick_remove_page(tempvaddr);
1494 				bpage = STAILQ_NEXT(bpage, links);
1495 			}
1496 			dmat->bounce_zone->total_bounced++;
1497 		}
1498 	}
1499 
1500 	/*
1501 	 * For COHERENT memory no cache maintenance is necessary, but ensure all
1502 	 * writes have reached memory for the PREWRITE case.  No action is
1503 	 * needed for a PREREAD without PREWRITE also set, because that would
1504 	 * imply that the cpu had written to the COHERENT buffer and expected
1505 	 * the dma device to see that change, and by definition a PREWRITE sync
1506 	 * is required to make that happen.
1507 	 */
1508 	if (map->flags & DMAMAP_COHERENT) {
1509 		if (op & BUS_DMASYNC_PREWRITE) {
1510 			dsb();
1511 			if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1512 				cpu_l2cache_drain_writebuf();
1513 		}
1514 		return;
1515 	}
1516 
1517 	/*
1518 	 * Cache maintenance for normal (non-COHERENT non-bounce) buffers.  All
1519 	 * the comments about the sequences for flushing cache levels in the
1520 	 * bounce buffer code above apply here as well.  In particular, the fact
1521 	 * that the sequence is inner-to-outer for PREREAD invalidation and
1522 	 * outer-to-inner for POSTREAD invalidation is not a mistake.
1523 	 */
1524 	if (map->sync_count != 0) {
1525 		sl = &map->slist[0];
1526 		end = &map->slist[map->sync_count];
1527 		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1528 		    "performing sync", __func__, dmat, dmat->flags, op);
1529 
1530 		for ( ; sl != end; ++sl)
1531 			dma_dcache_sync(sl, op);
1532 	}
1533 }
1534 
1535 static void
1536 init_bounce_pages(void *dummy __unused)
1537 {
1538 
1539 	total_bpages = 0;
1540 	STAILQ_INIT(&bounce_zone_list);
1541 	STAILQ_INIT(&bounce_map_waitinglist);
1542 	STAILQ_INIT(&bounce_map_callbacklist);
1543 	mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
1544 }
1545 SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
1546 
1547 static struct sysctl_ctx_list *
1548 busdma_sysctl_tree(struct bounce_zone *bz)
1549 {
1550 
1551 	return (&bz->sysctl_tree);
1552 }
1553 
1554 static struct sysctl_oid *
1555 busdma_sysctl_tree_top(struct bounce_zone *bz)
1556 {
1557 
1558 	return (bz->sysctl_tree_top);
1559 }
1560 
1561 static int
1562 alloc_bounce_zone(bus_dma_tag_t dmat)
1563 {
1564 	struct bounce_zone *bz;
1565 
1566 	/* Check to see if we already have a suitable zone */
1567 	STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1568 		if ((dmat->alignment <= bz->alignment) &&
1569 		    (dmat->lowaddr >= bz->lowaddr)) {
1570 			dmat->bounce_zone = bz;
1571 			return (0);
1572 		}
1573 	}
1574 
1575 	if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_BUSDMA,
1576 	    M_NOWAIT | M_ZERO)) == NULL)
1577 		return (ENOMEM);
1578 
1579 	STAILQ_INIT(&bz->bounce_page_list);
1580 	bz->free_bpages = 0;
1581 	bz->reserved_bpages = 0;
1582 	bz->active_bpages = 0;
1583 	bz->lowaddr = dmat->lowaddr;
1584 	bz->alignment = MAX(dmat->alignment, PAGE_SIZE);
1585 	bz->map_count = 0;
1586 	snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1587 	busdma_zonecount++;
1588 	snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1589 	STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1590 	dmat->bounce_zone = bz;
1591 
1592 	sysctl_ctx_init(&bz->sysctl_tree);
1593 	bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
1594 	    SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1595 	    CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
1596 	if (bz->sysctl_tree_top == NULL) {
1597 		sysctl_ctx_free(&bz->sysctl_tree);
1598 		return (0);	/* XXX error code? */
1599 	}
1600 
1601 	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1602 	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1603 	    "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1604 	    "Total bounce pages");
1605 	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1606 	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1607 	    "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1608 	    "Free bounce pages");
1609 	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1610 	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1611 	    "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1612 	    "Reserved bounce pages");
1613 	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1614 	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1615 	    "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1616 	    "Active bounce pages");
1617 	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1618 	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1619 	    "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1620 	    "Total bounce requests (pages bounced)");
1621 	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1622 	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1623 	    "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1624 	    "Total bounce requests that were deferred");
1625 	SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1626 	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1627 	    "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1628 	SYSCTL_ADD_ULONG(busdma_sysctl_tree(bz),
1629 	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1630 	    "alignment", CTLFLAG_RD, &bz->alignment, "");
1631 
1632 	return (0);
1633 }
1634 
1635 static int
1636 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1637 {
1638 	struct bounce_zone *bz;
1639 	int count;
1640 
1641 	bz = dmat->bounce_zone;
1642 	count = 0;
1643 	while (numpages > 0) {
1644 		struct bounce_page *bpage;
1645 
1646 		bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_BUSDMA,
1647 		    M_NOWAIT | M_ZERO);
1648 
1649 		if (bpage == NULL)
1650 			break;
1651 		bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_BOUNCE,
1652 		    M_NOWAIT, 0ul, bz->lowaddr, PAGE_SIZE, 0);
1653 		if (bpage->vaddr == 0) {
1654 			free(bpage, M_BUSDMA);
1655 			break;
1656 		}
1657 		bpage->busaddr = pmap_kextract(bpage->vaddr);
1658 		mtx_lock(&bounce_lock);
1659 		STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1660 		total_bpages++;
1661 		bz->total_bpages++;
1662 		bz->free_bpages++;
1663 		mtx_unlock(&bounce_lock);
1664 		count++;
1665 		numpages--;
1666 	}
1667 	return (count);
1668 }
1669 
1670 static int
1671 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1672 {
1673 	struct bounce_zone *bz;
1674 	int pages;
1675 
1676 	mtx_assert(&bounce_lock, MA_OWNED);
1677 	bz = dmat->bounce_zone;
1678 	pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1679 	if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1680 		return (map->pagesneeded - (map->pagesreserved + pages));
1681 	bz->free_bpages -= pages;
1682 	bz->reserved_bpages += pages;
1683 	map->pagesreserved += pages;
1684 	pages = map->pagesneeded - map->pagesreserved;
1685 
1686 	return (pages);
1687 }
1688 
1689 static bus_addr_t
1690 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1691     bus_addr_t addr, bus_size_t size)
1692 {
1693 	struct bounce_zone *bz;
1694 	struct bounce_page *bpage;
1695 
1696 	KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1697 	KASSERT(map != NULL, ("add_bounce_page: bad map %p", map));
1698 
1699 	bz = dmat->bounce_zone;
1700 	if (map->pagesneeded == 0)
1701 		panic("add_bounce_page: map doesn't need any pages");
1702 	map->pagesneeded--;
1703 
1704 	if (map->pagesreserved == 0)
1705 		panic("add_bounce_page: map doesn't need any pages");
1706 	map->pagesreserved--;
1707 
1708 	mtx_lock(&bounce_lock);
1709 	bpage = STAILQ_FIRST(&bz->bounce_page_list);
1710 	if (bpage == NULL)
1711 		panic("add_bounce_page: free page list is empty");
1712 
1713 	STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1714 	bz->reserved_bpages--;
1715 	bz->active_bpages++;
1716 	mtx_unlock(&bounce_lock);
1717 
1718 	if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1719 		/* Page offset needs to be preserved. */
1720 		bpage->vaddr |= addr & PAGE_MASK;
1721 		bpage->busaddr |= addr & PAGE_MASK;
1722 	}
1723 	bpage->datavaddr = vaddr;
1724 	bpage->datapage = PHYS_TO_VM_PAGE(addr);
1725 	bpage->dataoffs = addr & PAGE_MASK;
1726 	bpage->datacount = size;
1727 	STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1728 	return (bpage->busaddr);
1729 }
1730 
1731 static void
1732 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1733 {
1734 	struct bus_dmamap *map;
1735 	struct bounce_zone *bz;
1736 
1737 	bz = dmat->bounce_zone;
1738 	bpage->datavaddr = 0;
1739 	bpage->datacount = 0;
1740 	if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1741 		/*
1742 		 * Reset the bounce page to start at offset 0.  Other uses
1743 		 * of this bounce page may need to store a full page of
1744 		 * data and/or assume it starts on a page boundary.
1745 		 */
1746 		bpage->vaddr &= ~PAGE_MASK;
1747 		bpage->busaddr &= ~PAGE_MASK;
1748 	}
1749 
1750 	mtx_lock(&bounce_lock);
1751 	STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1752 	bz->free_bpages++;
1753 	bz->active_bpages--;
1754 	if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1755 		if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1756 			STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1757 			STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1758 			    map, links);
1759 			busdma_swi_pending = 1;
1760 			bz->total_deferred++;
1761 			swi_sched(vm_ih, 0);
1762 		}
1763 	}
1764 	mtx_unlock(&bounce_lock);
1765 }
1766 
1767 void
1768 busdma_swi(void)
1769 {
1770 	bus_dma_tag_t dmat;
1771 	struct bus_dmamap *map;
1772 
1773 	mtx_lock(&bounce_lock);
1774 	while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1775 		STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1776 		mtx_unlock(&bounce_lock);
1777 		dmat = map->dmat;
1778 		dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_LOCK);
1779 		bus_dmamap_load_mem(map->dmat, map, &map->mem, map->callback,
1780 		    map->callback_arg, BUS_DMA_WAITOK);
1781 		dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_UNLOCK);
1782 		mtx_lock(&bounce_lock);
1783 	}
1784 	mtx_unlock(&bounce_lock);
1785 }
1786