1 /*
2  * Copyright (c) 1997, 1998 Justin T. Gibbs.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions, and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. The name of the author may not be used to endorse or promote products
12  *    derived from this software without specific prior written permission.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
18  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/i386/i386/busdma_machdep.c,v 1.94 2008/08/15 20:51:31 kmacy Exp $
27  */
28 
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/malloc.h>
32 #include <sys/mbuf.h>
33 #include <sys/uio.h>
34 #include <sys/bus_dma.h>
35 #include <sys/kernel.h>
36 #include <sys/sysctl.h>
37 #include <sys/lock.h>
38 
39 #include <sys/thread2.h>
40 #include <sys/spinlock2.h>
41 #include <sys/mplock2.h>
42 
43 #include <vm/vm.h>
44 #include <vm/vm_page.h>
45 
46 /* XXX needed for to access pmap to convert per-proc virtual to physical */
47 #include <sys/proc.h>
48 #include <vm/vm_map.h>
49 
50 #include <machine/md_var.h>
51 
52 #define MAX_BPAGES	1024
53 
54 /*
55  * 16 x N declared on stack.
56  */
57 #define	BUS_DMA_CACHE_SEGMENTS	8
58 
59 struct bounce_zone;
60 struct bus_dmamap;
61 
62 struct bus_dma_tag {
63 	bus_dma_tag_t	parent;
64 	bus_size_t	alignment;
65 	bus_size_t	boundary;
66 	bus_addr_t	lowaddr;
67 	bus_addr_t	highaddr;
68 	bus_dma_filter_t *filter;
69 	void		*filterarg;
70 	bus_size_t	maxsize;
71 	u_int		nsegments;
72 	bus_size_t	maxsegsz;
73 	int		flags;
74 	int		ref_count;
75 	int		map_count;
76 	bus_dma_segment_t *segments;
77 	struct bounce_zone *bounce_zone;
78 	struct spinlock	spin;
79 };
80 
81 /*
82  * bus_dma_tag private flags
83  */
84 #define BUS_DMA_BOUNCE_ALIGN	BUS_DMA_BUS2
85 #define BUS_DMA_BOUNCE_LOWADDR	BUS_DMA_BUS3
86 #define BUS_DMA_MIN_ALLOC_COMP	BUS_DMA_BUS4
87 
88 #define BUS_DMA_COULD_BOUNCE	(BUS_DMA_BOUNCE_LOWADDR | BUS_DMA_BOUNCE_ALIGN)
89 
90 #define BUS_DMAMEM_KMALLOC(dmat) \
91 	((dmat)->maxsize <= PAGE_SIZE && \
92 	 (dmat)->alignment <= PAGE_SIZE && \
93 	 (dmat)->lowaddr >= ptoa(Maxmem))
94 
95 struct bounce_page {
96 	vm_offset_t	vaddr;		/* kva of bounce buffer */
97 	bus_addr_t	busaddr;	/* Physical address */
98 	vm_offset_t	datavaddr;	/* kva of client data */
99 	bus_size_t	datacount;	/* client data count */
100 	STAILQ_ENTRY(bounce_page) links;
101 };
102 
103 struct bounce_zone {
104 	STAILQ_ENTRY(bounce_zone) links;
105 	STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
106 	STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
107 	struct spinlock	spin;
108 	int		total_bpages;
109 	int		free_bpages;
110 	int		reserved_bpages;
111 	int		active_bpages;
112 	int		total_bounced;
113 	int		total_deferred;
114 	int		reserve_failed;
115 	bus_size_t	alignment;
116 	bus_addr_t	lowaddr;
117 	char		zoneid[8];
118 	char		lowaddrid[20];
119 	struct sysctl_ctx_list sysctl_ctx;
120 	struct sysctl_oid *sysctl_tree;
121 };
122 
123 #define BZ_LOCK(bz)	spin_lock(&(bz)->spin)
124 #define BZ_UNLOCK(bz)	spin_unlock(&(bz)->spin)
125 
126 static struct lwkt_token bounce_zone_tok =
127 	LWKT_TOKEN_INITIALIZER(bounce_zone_token);
128 static int busdma_zonecount;
129 static STAILQ_HEAD(, bounce_zone) bounce_zone_list =
130 	STAILQ_HEAD_INITIALIZER(bounce_zone_list);
131 
132 static int busdma_priv_zonecount = -1;
133 
134 int busdma_swi_pending;
135 static int total_bounce_pages;
136 static int max_bounce_pages = MAX_BPAGES;
137 static int bounce_alignment = 1; /* XXX temporary */
138 
139 TUNABLE_INT("hw.busdma.max_bpages", &max_bounce_pages);
140 TUNABLE_INT("hw.busdma.bounce_alignment", &bounce_alignment);
141 
142 struct bus_dmamap {
143 	struct bp_list	bpages;
144 	int		pagesneeded;
145 	int		pagesreserved;
146 	bus_dma_tag_t	dmat;
147 	void		*buf;		/* unmapped buffer pointer */
148 	bus_size_t	buflen;		/* unmapped buffer length */
149 	bus_dmamap_callback_t *callback;
150 	void		*callback_arg;
151 	STAILQ_ENTRY(bus_dmamap) links;
152 };
153 
154 static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist =
155 	STAILQ_HEAD_INITIALIZER(bounce_map_callbacklist);
156 static struct spinlock bounce_map_list_spin =
157 	SPINLOCK_INITIALIZER(&bounce_map_list_spin);
158 
159 static struct bus_dmamap nobounce_dmamap;
160 
161 static int		alloc_bounce_zone(bus_dma_tag_t);
162 static int		alloc_bounce_pages(bus_dma_tag_t, u_int, int);
163 static void		free_bounce_pages_all(bus_dma_tag_t);
164 static void		free_bounce_zone(bus_dma_tag_t);
165 static int		reserve_bounce_pages(bus_dma_tag_t, bus_dmamap_t, int);
166 static void		return_bounce_pages(bus_dma_tag_t, bus_dmamap_t);
167 static bus_addr_t	add_bounce_page(bus_dma_tag_t, bus_dmamap_t,
168 			    vm_offset_t, bus_size_t);
169 static void		free_bounce_page(bus_dma_tag_t, struct bounce_page *);
170 
171 static bus_dmamap_t	get_map_waiting(bus_dma_tag_t);
172 static void		add_map_callback(bus_dmamap_t);
173 
174 SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
175 SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bounce_pages,
176 	   0, "Total bounce pages");
177 SYSCTL_INT(_hw_busdma, OID_AUTO, max_bpages, CTLFLAG_RD, &max_bounce_pages,
178 	   0, "Max bounce pages per bounce zone");
179 SYSCTL_INT(_hw_busdma, OID_AUTO, bounce_alignment, CTLFLAG_RD,
180 	   &bounce_alignment, 0, "Obey alignment constraint");
181 
182 static __inline int
183 run_filter(bus_dma_tag_t dmat, bus_addr_t paddr)
184 {
185 	int retval;
186 
187 	retval = 0;
188 	do {
189 		if (((paddr > dmat->lowaddr && paddr <= dmat->highaddr) ||
190 		     (bounce_alignment && (paddr & (dmat->alignment - 1)) != 0))
191 		 && (dmat->filter == NULL ||
192 		     dmat->filter(dmat->filterarg, paddr) != 0))
193 			retval = 1;
194 
195 		dmat = dmat->parent;
196 	} while (retval == 0 && dmat != NULL);
197 	return (retval);
198 }
199 
200 static __inline
201 bus_dma_segment_t *
202 bus_dma_tag_lock(bus_dma_tag_t tag, bus_dma_segment_t *cache)
203 {
204 	if (tag->flags & BUS_DMA_PROTECTED)
205 		return(tag->segments);
206 
207 	if (tag->nsegments <= BUS_DMA_CACHE_SEGMENTS)
208 		return(cache);
209 	spin_lock(&tag->spin);
210 	return(tag->segments);
211 }
212 
213 static __inline
214 void
215 bus_dma_tag_unlock(bus_dma_tag_t tag)
216 {
217 	if (tag->flags & BUS_DMA_PROTECTED)
218 		return;
219 
220 	if (tag->nsegments > BUS_DMA_CACHE_SEGMENTS)
221 		spin_unlock(&tag->spin);
222 }
223 
224 /*
225  * Allocate a device specific dma_tag.
226  */
227 int
228 bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
229 		   bus_size_t boundary, bus_addr_t lowaddr,
230 		   bus_addr_t highaddr, bus_dma_filter_t *filter,
231 		   void *filterarg, bus_size_t maxsize, int nsegments,
232 		   bus_size_t maxsegsz, int flags, bus_dma_tag_t *dmat)
233 {
234 	bus_dma_tag_t newtag;
235 	int error = 0;
236 
237 	/*
238 	 * Sanity checks
239 	 */
240 
241 	if (alignment == 0)
242 		alignment = 1;
243 	if (alignment & (alignment - 1))
244 		panic("alignment must be power of 2");
245 
246 	if (boundary != 0) {
247 		if (boundary & (boundary - 1))
248 			panic("boundary must be power of 2");
249 		if (boundary < maxsegsz) {
250 			kprintf("boundary < maxsegsz:\n");
251 			print_backtrace(-1);
252 			maxsegsz = boundary;
253 		}
254 	}
255 
256 	/* Return a NULL tag on failure */
257 	*dmat = NULL;
258 
259 	newtag = kmalloc(sizeof(*newtag), M_DEVBUF, M_INTWAIT | M_ZERO);
260 
261 	spin_init(&newtag->spin);
262 	newtag->parent = parent;
263 	newtag->alignment = alignment;
264 	newtag->boundary = boundary;
265 	newtag->lowaddr = trunc_page((vm_paddr_t)lowaddr) + (PAGE_SIZE - 1);
266 	newtag->highaddr = trunc_page((vm_paddr_t)highaddr) + (PAGE_SIZE - 1);
267 	newtag->filter = filter;
268 	newtag->filterarg = filterarg;
269 	newtag->maxsize = maxsize;
270 	newtag->nsegments = nsegments;
271 	newtag->maxsegsz = maxsegsz;
272 	newtag->flags = flags;
273 	newtag->ref_count = 1; /* Count ourself */
274 	newtag->map_count = 0;
275 	newtag->segments = NULL;
276 	newtag->bounce_zone = NULL;
277 
278 	/* Take into account any restrictions imposed by our parent tag */
279 	if (parent != NULL) {
280 		newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
281 		newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
282 
283 		if (newtag->boundary == 0) {
284 			newtag->boundary = parent->boundary;
285 		} else if (parent->boundary != 0) {
286 			newtag->boundary = MIN(parent->boundary,
287 					       newtag->boundary);
288 		}
289 
290 #ifdef notyet
291 		newtag->alignment = MAX(parent->alignment, newtag->alignment);
292 #endif
293 
294 		if (newtag->filter == NULL) {
295 			/*
296 			 * Short circuit looking at our parent directly
297 			 * since we have encapsulated all of its information
298 			 */
299 			newtag->filter = parent->filter;
300 			newtag->filterarg = parent->filterarg;
301 			newtag->parent = parent->parent;
302 		}
303 		if (newtag->parent != NULL)
304 			parent->ref_count++;
305 	}
306 
307 	if (newtag->lowaddr < ptoa(Maxmem))
308 		newtag->flags |= BUS_DMA_BOUNCE_LOWADDR;
309 	if (bounce_alignment && newtag->alignment > 1 &&
310 	    !(newtag->flags & BUS_DMA_ALIGNED))
311 		newtag->flags |= BUS_DMA_BOUNCE_ALIGN;
312 
313 	if ((newtag->flags & BUS_DMA_COULD_BOUNCE) &&
314 	    (flags & BUS_DMA_ALLOCNOW) != 0) {
315 		struct bounce_zone *bz;
316 
317 		/* Must bounce */
318 
319 		error = alloc_bounce_zone(newtag);
320 		if (error)
321 			goto back;
322 		bz = newtag->bounce_zone;
323 
324 		if ((newtag->flags & BUS_DMA_ALLOCALL) == 0 &&
325 		    ptoa(bz->total_bpages) < maxsize) {
326 			int pages;
327 
328 			if (flags & BUS_DMA_ONEBPAGE) {
329 				pages = 1;
330 			} else {
331 				pages = atop(round_page(maxsize)) -
332 					bz->total_bpages;
333 				pages = MAX(pages, 1);
334 			}
335 
336 			/* Add pages to our bounce pool */
337 			if (alloc_bounce_pages(newtag, pages, flags) < pages)
338 				error = ENOMEM;
339 
340 			/* Performed initial allocation */
341 			newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
342 		}
343 	}
344 back:
345 	if (error) {
346 		free_bounce_zone(newtag);
347 		kfree(newtag, M_DEVBUF);
348 	} else {
349 		*dmat = newtag;
350 	}
351 	return error;
352 }
353 
354 int
355 bus_dma_tag_destroy(bus_dma_tag_t dmat)
356 {
357 	if (dmat != NULL) {
358 		if (dmat->map_count != 0)
359 			return (EBUSY);
360 
361 		while (dmat != NULL) {
362 			bus_dma_tag_t parent;
363 
364 			parent = dmat->parent;
365 			dmat->ref_count--;
366 			if (dmat->ref_count == 0) {
367 				free_bounce_zone(dmat);
368 				if (dmat->segments != NULL)
369 					kfree(dmat->segments, M_DEVBUF);
370 				kfree(dmat, M_DEVBUF);
371 				/*
372 				 * Last reference count, so
373 				 * release our reference
374 				 * count on our parent.
375 				 */
376 				dmat = parent;
377 			} else
378 				dmat = NULL;
379 		}
380 	}
381 	return (0);
382 }
383 
384 bus_size_t
385 bus_dma_tag_getmaxsize(bus_dma_tag_t tag)
386 {
387 	return(tag->maxsize);
388 }
389 
390 /*
391  * Allocate a handle for mapping from kva/uva/physical
392  * address space into bus device space.
393  */
394 int
395 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
396 {
397 	int error;
398 
399 	error = 0;
400 
401 	if (dmat->segments == NULL) {
402 		KKASSERT(dmat->nsegments && dmat->nsegments < 16384);
403 		dmat->segments = kmalloc(sizeof(bus_dma_segment_t) *
404 					dmat->nsegments, M_DEVBUF, M_INTWAIT);
405 	}
406 
407 	if (dmat->flags & BUS_DMA_COULD_BOUNCE) {
408 		struct bounce_zone *bz;
409 		int maxpages;
410 
411 		/* Must bounce */
412 
413 		if (dmat->bounce_zone == NULL) {
414 			error = alloc_bounce_zone(dmat);
415 			if (error)
416 				return error;
417 		}
418 		bz = dmat->bounce_zone;
419 
420 		*mapp = kmalloc(sizeof(**mapp), M_DEVBUF, M_INTWAIT | M_ZERO);
421 
422 		/* Initialize the new map */
423 		STAILQ_INIT(&((*mapp)->bpages));
424 
425 		/*
426 		 * Attempt to add pages to our pool on a per-instance
427 		 * basis up to a sane limit.
428 		 */
429 		if (dmat->flags & BUS_DMA_ALLOCALL) {
430 			maxpages = Maxmem - atop(dmat->lowaddr);
431 		} else if (dmat->flags & BUS_DMA_BOUNCE_ALIGN) {
432 			maxpages = max_bounce_pages;
433 		} else {
434 			maxpages = MIN(max_bounce_pages,
435 				       Maxmem - atop(dmat->lowaddr));
436 		}
437 		if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0 ||
438 		    (dmat->map_count > 0 && bz->total_bpages < maxpages)) {
439 			int pages;
440 
441 			if (flags & BUS_DMA_ONEBPAGE) {
442 				pages = 1;
443 			} else {
444 				pages = atop(round_page(dmat->maxsize));
445 				pages = MIN(maxpages - bz->total_bpages, pages);
446 				pages = MAX(pages, 1);
447 			}
448 			if (alloc_bounce_pages(dmat, pages, flags) < pages)
449 				error = ENOMEM;
450 
451 			if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0) {
452 				if (!error &&
453 				    (dmat->flags & BUS_DMA_ALLOCALL) == 0)
454 					dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
455 			} else {
456 				error = 0;
457 			}
458 		}
459 	} else {
460 		*mapp = NULL;
461 	}
462 	if (!error) {
463 		dmat->map_count++;
464 	} else {
465 		kfree(*mapp, M_DEVBUF);
466 		*mapp = NULL;
467 	}
468 	return error;
469 }
470 
471 /*
472  * Destroy a handle for mapping from kva/uva/physical
473  * address space into bus device space.
474  */
475 int
476 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
477 {
478 	if (map != NULL) {
479 		if (STAILQ_FIRST(&map->bpages) != NULL)
480 			return (EBUSY);
481 		kfree(map, M_DEVBUF);
482 	}
483 	dmat->map_count--;
484 	return (0);
485 }
486 
487 static __inline bus_size_t
488 check_kmalloc(bus_dma_tag_t dmat, const void *vaddr0, int verify)
489 {
490 	bus_size_t maxsize = 0;
491 	uintptr_t vaddr = (uintptr_t)vaddr0;
492 
493 	if ((vaddr ^ (vaddr + dmat->maxsize - 1)) & ~PAGE_MASK) {
494 		if (verify)
495 			panic("boundary check failed\n");
496 		if (bootverbose)
497 			kprintf("boundary check failed\n");
498 		maxsize = dmat->maxsize;
499 	}
500 	if (vaddr & (dmat->alignment - 1)) {
501 		if (verify)
502 			panic("alignment check failed\n");
503 		if (bootverbose)
504 			kprintf("alignment check failed\n");
505 		if (dmat->maxsize < dmat->alignment)
506 			maxsize = dmat->alignment;
507 		else
508 			maxsize = dmat->maxsize;
509 	}
510 	return maxsize;
511 }
512 
513 /*
514  * Allocate a piece of memory that can be efficiently mapped into
515  * bus device space based on the constraints lited in the dma tag.
516  *
517  * mapp is degenerate.  By definition this allocation should not require
518  * bounce buffers so do not allocate a dma map.
519  */
520 int
521 bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
522 		 bus_dmamap_t *mapp)
523 {
524 	vm_memattr_t attr;
525 	int mflags;
526 
527 	/* If we succeed, no mapping/bouncing will be required */
528 	*mapp = NULL;
529 
530 	if (dmat->segments == NULL) {
531 		KKASSERT(dmat->nsegments < 16384);
532 		dmat->segments = kmalloc(sizeof(bus_dma_segment_t) *
533 					dmat->nsegments, M_DEVBUF, M_INTWAIT);
534 	}
535 
536 	if (flags & BUS_DMA_NOWAIT)
537 		mflags = M_NOWAIT;
538 	else
539 		mflags = M_WAITOK;
540 	if (flags & BUS_DMA_ZERO)
541 		mflags |= M_ZERO;
542 	if (flags & BUS_DMA_NOCACHE)
543 		attr = VM_MEMATTR_UNCACHEABLE;
544 	else
545 		attr = VM_MEMATTR_DEFAULT;
546 
547 	/* XXX must alloc with correct mem attribute here */
548 	if (BUS_DMAMEM_KMALLOC(dmat)) {
549 		bus_size_t maxsize;
550 
551 		*vaddr = kmalloc(dmat->maxsize, M_DEVBUF, mflags);
552 
553 		/*
554 		 * XXX
555 		 * Check whether the allocation
556 		 * - crossed a page boundary
557 		 * - was not aligned
558 		 * Retry with power-of-2 alignment in the above cases.
559 		 */
560 		maxsize = check_kmalloc(dmat, *vaddr, 0);
561 		if (maxsize) {
562 			kfree(*vaddr, M_DEVBUF);
563 			*vaddr = kmalloc(maxsize, M_DEVBUF,
564 			    mflags | M_POWEROF2);
565 			check_kmalloc(dmat, *vaddr, 1);
566 		}
567 	} else {
568 		/*
569 		 * XXX Use Contigmalloc until it is merged into this facility
570 		 *     and handles multi-seg allocations.  Nobody is doing
571 		 *     multi-seg allocations yet though.
572 		 */
573 		*vaddr = contigmalloc(dmat->maxsize, M_DEVBUF, mflags,
574 		    0ul, dmat->lowaddr, dmat->alignment, dmat->boundary);
575 	}
576 	if (*vaddr == NULL)
577 		return (ENOMEM);
578 
579 	/* XXX: BUS_DMA_NOCACHE */
580 	if (attr != VM_MEMATTR_DEFAULT)
581 		pmap_change_attr((vm_offset_t)vaddr, dmat->maxsize / PAGE_SIZE, attr);
582 	return (0);
583 }
584 
585 /*
586  * Free a piece of memory and it's allociated dmamap, that was allocated
587  * via bus_dmamem_alloc.  Make the same choice for free/contigfree.
588  */
589 void
590 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
591 {
592 	/*
593 	 * dmamem does not need to be bounced, so the map should be
594 	 * NULL
595 	 */
596 	if (map != NULL)
597 		panic("bus_dmamem_free: Invalid map freed");
598 	if (BUS_DMAMEM_KMALLOC(dmat))
599 		kfree(vaddr, M_DEVBUF);
600 	else
601 		contigfree(vaddr, dmat->maxsize, M_DEVBUF);
602 }
603 
604 static __inline vm_paddr_t
605 _bus_dma_extract(pmap_t pmap, vm_offset_t vaddr)
606 {
607 	if (pmap)
608 		return pmap_extract(pmap, vaddr);
609 	else
610 		return pmap_kextract(vaddr);
611 }
612 
613 /*
614  * Utility function to load a linear buffer.  lastaddrp holds state
615  * between invocations (for multiple-buffer loads).  segp contains
616  * the segment following the starting one on entrace, and the ending
617  * segment on exit.  first indicates if this is the first invocation
618  * of this function.
619  */
620 static int
621 _bus_dmamap_load_buffer(bus_dma_tag_t dmat,
622 			bus_dmamap_t map,
623 			void *buf, bus_size_t buflen,
624 			bus_dma_segment_t *segments,
625 			int nsegments,
626 			pmap_t pmap,
627 			int flags,
628 			vm_paddr_t *lastpaddrp,
629 			int *segp,
630 			int first)
631 {
632 	vm_offset_t vaddr;
633 	vm_paddr_t paddr, nextpaddr;
634 	bus_dma_segment_t *sg;
635 	bus_addr_t bmask;
636 	int seg, error = 0;
637 
638 	if (map == NULL)
639 		map = &nobounce_dmamap;
640 
641 #ifdef INVARIANTS
642 	if (dmat->flags & BUS_DMA_ALIGNED)
643 		KKASSERT(((uintptr_t)buf & (dmat->alignment - 1)) == 0);
644 #endif
645 
646 	/*
647 	 * If we are being called during a callback, pagesneeded will
648 	 * be non-zero, so we can avoid doing the work twice.
649 	 */
650 	if ((dmat->flags & BUS_DMA_COULD_BOUNCE) &&
651 	    map != &nobounce_dmamap && map->pagesneeded == 0) {
652 		vm_offset_t vendaddr;
653 
654 		/*
655 		 * Count the number of bounce pages
656 		 * needed in order to complete this transfer
657 		 */
658 		vaddr = (vm_offset_t)buf;
659 		vendaddr = (vm_offset_t)buf + buflen;
660 
661 		while (vaddr < vendaddr) {
662 			paddr = _bus_dma_extract(pmap, vaddr);
663 			if (run_filter(dmat, paddr) != 0)
664 				map->pagesneeded++;
665 			vaddr += (PAGE_SIZE - (vaddr & PAGE_MASK));
666 		}
667 	}
668 
669 	/* Reserve Necessary Bounce Pages */
670 	if (map->pagesneeded != 0) {
671 		struct bounce_zone *bz;
672 
673 		bz = dmat->bounce_zone;
674 		BZ_LOCK(bz);
675 		if (flags & BUS_DMA_NOWAIT) {
676 			if (reserve_bounce_pages(dmat, map, 0) != 0) {
677 				BZ_UNLOCK(bz);
678 				error = ENOMEM;
679 				goto free_bounce;
680 			}
681 		} else {
682 			if (reserve_bounce_pages(dmat, map, 1) != 0) {
683 				/* Queue us for resources */
684 				map->dmat = dmat;
685 				map->buf = buf;
686 				map->buflen = buflen;
687 
688 				STAILQ_INSERT_TAIL(
689 				    &dmat->bounce_zone->bounce_map_waitinglist,
690 				    map, links);
691 				BZ_UNLOCK(bz);
692 
693 				return (EINPROGRESS);
694 			}
695 		}
696 		BZ_UNLOCK(bz);
697 	}
698 
699 	KKASSERT(*segp >= 1 && *segp <= nsegments);
700 	seg = *segp;
701 	sg = &segments[seg - 1];
702 
703 	vaddr = (vm_offset_t)buf;
704 	nextpaddr = *lastpaddrp;
705 	bmask = ~(dmat->boundary - 1);	/* note: will be 0 if boundary is 0 */
706 
707 	/* force at least one segment */
708 	do {
709 		bus_size_t size;
710 
711 		/*
712 		 * Per-page main loop
713 		 */
714 		paddr = _bus_dma_extract(pmap, vaddr);
715 		size = PAGE_SIZE - (paddr & PAGE_MASK);
716 		if (size > buflen)
717 			size = buflen;
718 		if (map->pagesneeded != 0 && run_filter(dmat, paddr)) {
719 			/*
720 			 * note: this paddr has the same in-page offset
721 			 * as vaddr and thus the paddr above, so the
722 			 * size does not have to be recalculated
723 			 */
724 			paddr = add_bounce_page(dmat, map, vaddr, size);
725 		}
726 
727 		/*
728 		 * Fill in the bus_dma_segment
729 		 */
730 		if (first) {
731 			sg->ds_addr = paddr;
732 			sg->ds_len = size;
733 			first = 0;
734 		} else if (paddr == nextpaddr) {
735 			sg->ds_len += size;
736 		} else {
737 			sg++;
738 			seg++;
739 			if (seg > nsegments)
740 				break;
741 			sg->ds_addr = paddr;
742 			sg->ds_len = size;
743 		}
744 		nextpaddr = paddr + size;
745 
746 		/*
747 		 * Handle maxsegsz and boundary issues with a nested loop
748 		 */
749 		for (;;) {
750 			bus_size_t tmpsize;
751 
752 			/*
753 			 * Limit to the boundary and maximum segment size
754 			 */
755 			if (((nextpaddr - 1) ^ sg->ds_addr) & bmask) {
756 				tmpsize = dmat->boundary -
757 					  (sg->ds_addr & ~bmask);
758 				if (tmpsize > dmat->maxsegsz)
759 					tmpsize = dmat->maxsegsz;
760 				KKASSERT(tmpsize < sg->ds_len);
761 			} else if (sg->ds_len > dmat->maxsegsz) {
762 				tmpsize = dmat->maxsegsz;
763 			} else {
764 				break;
765 			}
766 
767 			/*
768 			 * Futz, split the data into a new segment.
769 			 */
770 			if (seg >= nsegments)
771 				goto fail;
772 			sg[1].ds_len = sg[0].ds_len - tmpsize;
773 			sg[1].ds_addr = sg[0].ds_addr + tmpsize;
774 			sg[0].ds_len = tmpsize;
775 			sg++;
776 			seg++;
777 		}
778 
779 		/*
780 		 * Adjust for loop
781 		 */
782 		buflen -= size;
783 		vaddr += size;
784 	} while (buflen > 0);
785 fail:
786 	if (buflen != 0)
787 		error = EFBIG;
788 
789 	*segp = seg;
790 	*lastpaddrp = nextpaddr;
791 
792 free_bounce:
793 	if (error && (dmat->flags & BUS_DMA_COULD_BOUNCE) &&
794 	    map != &nobounce_dmamap) {
795 		_bus_dmamap_unload(dmat, map);
796 		return_bounce_pages(dmat, map);
797 	}
798 	return error;
799 }
800 
801 /*
802  * Map the buffer buf into bus space using the dmamap map.
803  */
804 int
805 bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
806 		bus_size_t buflen, bus_dmamap_callback_t *callback,
807 		void *callback_arg, int flags)
808 {
809 	bus_dma_segment_t cache_segments[BUS_DMA_CACHE_SEGMENTS];
810 	bus_dma_segment_t *segments;
811 	vm_paddr_t lastaddr = 0;
812 	int error, nsegs = 1;
813 
814 	if (map != NULL) {
815 		/*
816 		 * XXX
817 		 * Follow old semantics.  Once all of the callers are fixed,
818 		 * we should get rid of these internal flag "adjustment".
819 		 */
820 		flags &= ~BUS_DMA_NOWAIT;
821 		flags |= BUS_DMA_WAITOK;
822 
823 		map->callback = callback;
824 		map->callback_arg = callback_arg;
825 	}
826 
827 	segments = bus_dma_tag_lock(dmat, cache_segments);
828 	error = _bus_dmamap_load_buffer(dmat, map, buf, buflen,
829 			segments, dmat->nsegments,
830 			NULL, flags, &lastaddr, &nsegs, 1);
831 	if (error == EINPROGRESS) {
832 		KKASSERT((dmat->flags &
833 			  (BUS_DMA_PRIVBZONE | BUS_DMA_ALLOCALL)) !=
834 			 (BUS_DMA_PRIVBZONE | BUS_DMA_ALLOCALL));
835 
836 		if (dmat->flags & BUS_DMA_PROTECTED)
837 			panic("protected dmamap callback will be defered");
838 
839 		bus_dma_tag_unlock(dmat);
840 		return error;
841 	}
842 	callback(callback_arg, segments, nsegs, error);
843 	bus_dma_tag_unlock(dmat);
844 	return 0;
845 }
846 
847 /*
848  * Like _bus_dmamap_load(), but for mbufs.
849  */
850 int
851 bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map,
852 		     struct mbuf *m0,
853 		     bus_dmamap_callback2_t *callback, void *callback_arg,
854 		     int flags)
855 {
856 	bus_dma_segment_t cache_segments[BUS_DMA_CACHE_SEGMENTS];
857 	bus_dma_segment_t *segments;
858 	int nsegs, error;
859 
860 	/*
861 	 * XXX
862 	 * Follow old semantics.  Once all of the callers are fixed,
863 	 * we should get rid of these internal flag "adjustment".
864 	 */
865 	flags &= ~BUS_DMA_WAITOK;
866 	flags |= BUS_DMA_NOWAIT;
867 
868 	segments = bus_dma_tag_lock(dmat, cache_segments);
869 	error = bus_dmamap_load_mbuf_segment(dmat, map, m0,
870 			segments, dmat->nsegments, &nsegs, flags);
871 	if (error) {
872 		/* force "no valid mappings" in callback */
873 		callback(callback_arg, segments, 0,
874 			 0, error);
875 	} else {
876 		callback(callback_arg, segments, nsegs,
877 			 m0->m_pkthdr.len, error);
878 	}
879 	bus_dma_tag_unlock(dmat);
880 	return error;
881 }
882 
883 int
884 bus_dmamap_load_mbuf_segment(bus_dma_tag_t dmat, bus_dmamap_t map,
885 			     struct mbuf *m0,
886 			     bus_dma_segment_t *segs, int maxsegs,
887 			     int *nsegs, int flags)
888 {
889 	int error;
890 
891 	M_ASSERTPKTHDR(m0);
892 
893 	KASSERT(maxsegs >= 1, ("invalid maxsegs %d", maxsegs));
894 	KASSERT(maxsegs <= dmat->nsegments,
895 		("%d too many segments, dmat only supports %d segments",
896 		 maxsegs, dmat->nsegments));
897 	KASSERT(flags & BUS_DMA_NOWAIT,
898 		("only BUS_DMA_NOWAIT is supported"));
899 
900 	if (m0->m_pkthdr.len <= dmat->maxsize) {
901 		int first = 1;
902 		vm_paddr_t lastaddr = 0;
903 		struct mbuf *m;
904 
905 		*nsegs = 1;
906 		error = 0;
907 		for (m = m0; m != NULL && error == 0; m = m->m_next) {
908 			if (m->m_len == 0)
909 				continue;
910 
911 			error = _bus_dmamap_load_buffer(dmat, map,
912 					m->m_data, m->m_len,
913 					segs, maxsegs,
914 					NULL, flags, &lastaddr,
915 					nsegs, first);
916 			if (error == ENOMEM && !first) {
917 				/*
918 				 * Out of bounce pages due to too many
919 				 * fragments in the mbuf chain; return
920 				 * EFBIG instead.
921 				 */
922 				error = EFBIG;
923 			}
924 			first = 0;
925 		}
926 #ifdef INVARIANTS
927 		if (!error)
928 			KKASSERT(*nsegs <= maxsegs && *nsegs >= 1);
929 #endif
930 	} else {
931 		*nsegs = 0;
932 		error = EINVAL;
933 	}
934 	KKASSERT(error != EINPROGRESS);
935 	return error;
936 }
937 
938 /*
939  * Like _bus_dmamap_load(), but for uios.
940  */
941 int
942 bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
943 		    struct uio *uio,
944 		    bus_dmamap_callback2_t *callback, void *callback_arg,
945 		    int flags)
946 {
947 	vm_paddr_t lastaddr;
948 	int nsegs, error, first, i;
949 	bus_size_t resid;
950 	struct iovec *iov;
951 	pmap_t pmap;
952 	bus_dma_segment_t cache_segments[BUS_DMA_CACHE_SEGMENTS];
953 	bus_dma_segment_t *segments;
954 	bus_dma_segment_t *segs;
955 	int nsegs_left;
956 
957 	if (dmat->nsegments <= BUS_DMA_CACHE_SEGMENTS)
958 		segments = cache_segments;
959 	else
960 		segments = kmalloc(sizeof(bus_dma_segment_t) * dmat->nsegments,
961 				   M_DEVBUF, M_WAITOK | M_ZERO);
962 
963 	/*
964 	 * XXX
965 	 * Follow old semantics.  Once all of the callers are fixed,
966 	 * we should get rid of these internal flag "adjustment".
967 	 */
968 	flags &= ~BUS_DMA_WAITOK;
969 	flags |= BUS_DMA_NOWAIT;
970 
971 	resid = (bus_size_t)uio->uio_resid;
972 	iov = uio->uio_iov;
973 
974 	segs = segments;
975 	nsegs_left = dmat->nsegments;
976 
977 	if (uio->uio_segflg == UIO_USERSPACE) {
978 		struct thread *td;
979 
980 		td = uio->uio_td;
981 		KASSERT(td != NULL && td->td_proc != NULL,
982 			("bus_dmamap_load_uio: USERSPACE but no proc"));
983 		pmap = vmspace_pmap(td->td_proc->p_vmspace);
984 	} else {
985 		pmap = NULL;
986 	}
987 
988 	error = 0;
989 	nsegs = 1;
990 	first = 1;
991 	lastaddr = 0;
992 	for (i = 0; i < uio->uio_iovcnt && resid != 0 && !error; i++) {
993 		/*
994 		 * Now at the first iovec to load.  Load each iovec
995 		 * until we have exhausted the residual count.
996 		 */
997 		bus_size_t minlen =
998 			resid < iov[i].iov_len ? resid : iov[i].iov_len;
999 		caddr_t addr = (caddr_t) iov[i].iov_base;
1000 
1001 		error = _bus_dmamap_load_buffer(dmat, map, addr, minlen,
1002 				segs, nsegs_left,
1003 				pmap, flags, &lastaddr, &nsegs, first);
1004 		first = 0;
1005 
1006 		resid -= minlen;
1007 		if (error == 0) {
1008 			nsegs_left -= nsegs;
1009 			segs += nsegs;
1010 		}
1011 	}
1012 
1013 	/*
1014 	 * Minimum one DMA segment, even if 0-length buffer.
1015 	 */
1016 	if (nsegs_left == dmat->nsegments)
1017 		--nsegs_left;
1018 
1019 	if (error) {
1020 		/* force "no valid mappings" in callback */
1021 		callback(callback_arg, segments, 0,
1022 			 0, error);
1023 	} else {
1024 		callback(callback_arg, segments, dmat->nsegments - nsegs_left,
1025 			 (bus_size_t)uio->uio_resid, error);
1026 	}
1027 	if (dmat->nsegments > BUS_DMA_CACHE_SEGMENTS)
1028 		kfree(segments, M_DEVBUF);
1029 	return error;
1030 }
1031 
1032 /*
1033  * Release the mapping held by map.
1034  */
1035 void
1036 _bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1037 {
1038 	struct bounce_page *bpage;
1039 
1040 	while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1041 		STAILQ_REMOVE_HEAD(&map->bpages, links);
1042 		free_bounce_page(dmat, bpage);
1043 	}
1044 }
1045 
1046 void
1047 _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1048 {
1049 	struct bounce_page *bpage;
1050 
1051 	if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1052 		/*
1053 		 * Handle data bouncing.  We might also
1054 		 * want to add support for invalidating
1055 		 * the caches on broken hardware
1056 		 */
1057 		switch (op) {
1058 		case BUS_DMASYNC_PREWRITE:
1059 			while (bpage != NULL) {
1060 				bcopy((void *)bpage->datavaddr,
1061 				      (void *)bpage->vaddr,
1062 				      bpage->datacount);
1063 				bpage = STAILQ_NEXT(bpage, links);
1064 			}
1065 			dmat->bounce_zone->total_bounced++;
1066 			break;
1067 
1068 		case BUS_DMASYNC_POSTREAD:
1069 			while (bpage != NULL) {
1070 				bcopy((void *)bpage->vaddr,
1071 				      (void *)bpage->datavaddr,
1072 				      bpage->datacount);
1073 				bpage = STAILQ_NEXT(bpage, links);
1074 			}
1075 			dmat->bounce_zone->total_bounced++;
1076 			break;
1077 
1078 		case BUS_DMASYNC_PREREAD:
1079 		case BUS_DMASYNC_POSTWRITE:
1080 			/* No-ops */
1081 			break;
1082 		}
1083 	}
1084 }
1085 
1086 static int
1087 alloc_bounce_zone(bus_dma_tag_t dmat)
1088 {
1089 	struct bounce_zone *bz, *new_bz;
1090 
1091 	KASSERT(dmat->bounce_zone == NULL,
1092 		("bounce zone was already assigned"));
1093 
1094 	new_bz = kmalloc(sizeof(*new_bz), M_DEVBUF, M_INTWAIT | M_ZERO);
1095 
1096 	lwkt_gettoken(&bounce_zone_tok);
1097 
1098 	if ((dmat->flags & BUS_DMA_PRIVBZONE) == 0) {
1099 		/*
1100 		 * For shared bounce zone, check to see
1101 		 * if we already have a suitable zone
1102 		 */
1103 		STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1104 			if (dmat->alignment <= bz->alignment &&
1105 			    dmat->lowaddr >= bz->lowaddr) {
1106 				lwkt_reltoken(&bounce_zone_tok);
1107 
1108 				dmat->bounce_zone = bz;
1109 				kfree(new_bz, M_DEVBUF);
1110 				return 0;
1111 			}
1112 		}
1113 	}
1114 	bz = new_bz;
1115 
1116 	spin_init(&bz->spin);
1117 	STAILQ_INIT(&bz->bounce_page_list);
1118 	STAILQ_INIT(&bz->bounce_map_waitinglist);
1119 	bz->free_bpages = 0;
1120 	bz->reserved_bpages = 0;
1121 	bz->active_bpages = 0;
1122 	bz->lowaddr = dmat->lowaddr;
1123 	bz->alignment = round_page(dmat->alignment);
1124 	ksnprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1125 
1126 	if ((dmat->flags & BUS_DMA_PRIVBZONE) == 0) {
1127 		ksnprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1128 		busdma_zonecount++;
1129 		STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1130 	} else {
1131 		ksnprintf(bz->zoneid, 8, "zone%d", busdma_priv_zonecount);
1132 		busdma_priv_zonecount--;
1133 	}
1134 
1135 	lwkt_reltoken(&bounce_zone_tok);
1136 
1137 	dmat->bounce_zone = bz;
1138 
1139 	sysctl_ctx_init(&bz->sysctl_ctx);
1140 	bz->sysctl_tree = SYSCTL_ADD_NODE(&bz->sysctl_ctx,
1141 	    SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1142 	    CTLFLAG_RD, 0, "");
1143 	if (bz->sysctl_tree == NULL) {
1144 		sysctl_ctx_free(&bz->sysctl_ctx);
1145 		return 0;	/* XXX error code? */
1146 	}
1147 
1148 	SYSCTL_ADD_INT(&bz->sysctl_ctx,
1149 	    SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1150 	    "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1151 	    "Total bounce pages");
1152 	SYSCTL_ADD_INT(&bz->sysctl_ctx,
1153 	    SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1154 	    "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1155 	    "Free bounce pages");
1156 	SYSCTL_ADD_INT(&bz->sysctl_ctx,
1157 	    SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1158 	    "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1159 	    "Reserved bounce pages");
1160 	SYSCTL_ADD_INT(&bz->sysctl_ctx,
1161 	    SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1162 	    "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1163 	    "Active bounce pages");
1164 	SYSCTL_ADD_INT(&bz->sysctl_ctx,
1165 	    SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1166 	    "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1167 	    "Total bounce requests");
1168 	SYSCTL_ADD_INT(&bz->sysctl_ctx,
1169 	    SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1170 	    "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1171 	    "Total bounce requests that were deferred");
1172 	SYSCTL_ADD_INT(&bz->sysctl_ctx,
1173 	    SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1174 	    "reserve_failed", CTLFLAG_RD, &bz->reserve_failed, 0,
1175 	    "Total bounce page reservations that were failed");
1176 	SYSCTL_ADD_STRING(&bz->sysctl_ctx,
1177 	    SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1178 	    "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1179 	SYSCTL_ADD_INT(&bz->sysctl_ctx,
1180 	    SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1181 	    "alignment", CTLFLAG_RD, &bz->alignment, 0, "");
1182 
1183 	return 0;
1184 }
1185 
1186 static int
1187 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages, int flags)
1188 {
1189 	struct bounce_zone *bz = dmat->bounce_zone;
1190 	int count = 0, mflags;
1191 
1192 	if (flags & BUS_DMA_NOWAIT)
1193 		mflags = M_NOWAIT;
1194 	else
1195 		mflags = M_WAITOK;
1196 
1197 	while (numpages > 0) {
1198 		struct bounce_page *bpage;
1199 
1200 		bpage = kmalloc(sizeof(*bpage), M_DEVBUF, M_INTWAIT | M_ZERO);
1201 
1202 		bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
1203 							 mflags, 0ul,
1204 							 bz->lowaddr,
1205 							 bz->alignment, 0);
1206 		if (bpage->vaddr == 0) {
1207 			kfree(bpage, M_DEVBUF);
1208 			break;
1209 		}
1210 		bpage->busaddr = pmap_kextract(bpage->vaddr);
1211 
1212 		BZ_LOCK(bz);
1213 		STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1214 		total_bounce_pages++;
1215 		bz->total_bpages++;
1216 		bz->free_bpages++;
1217 		BZ_UNLOCK(bz);
1218 
1219 		count++;
1220 		numpages--;
1221 	}
1222 	return count;
1223 }
1224 
1225 static void
1226 free_bounce_pages_all(bus_dma_tag_t dmat)
1227 {
1228 	struct bounce_zone *bz = dmat->bounce_zone;
1229 	struct bounce_page *bpage;
1230 
1231 	BZ_LOCK(bz);
1232 
1233 	while ((bpage = STAILQ_FIRST(&bz->bounce_page_list)) != NULL) {
1234 		STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1235 
1236 		KKASSERT(total_bounce_pages > 0);
1237 		total_bounce_pages--;
1238 
1239 		KKASSERT(bz->total_bpages > 0);
1240 		bz->total_bpages--;
1241 
1242 		KKASSERT(bz->free_bpages > 0);
1243 		bz->free_bpages--;
1244 
1245 		BZ_UNLOCK(bz);
1246 		contigfree((void *)bpage->vaddr, PAGE_SIZE, M_DEVBUF);
1247 		kfree(bpage, M_DEVBUF);
1248 		BZ_LOCK(bz);
1249 	}
1250 	if (bz->total_bpages) {
1251 		kprintf("#%d bounce pages are still in use\n",
1252 			bz->total_bpages);
1253 		print_backtrace(-1);
1254 	}
1255 
1256 	BZ_UNLOCK(bz);
1257 }
1258 
1259 static void
1260 free_bounce_zone(bus_dma_tag_t dmat)
1261 {
1262 	struct bounce_zone *bz = dmat->bounce_zone;
1263 
1264 	if (bz == NULL)
1265 		return;
1266 
1267 	if ((dmat->flags & BUS_DMA_PRIVBZONE) == 0)
1268 		return;
1269 
1270 	free_bounce_pages_all(dmat);
1271 	dmat->bounce_zone = NULL;
1272 
1273 	if (bz->sysctl_tree != NULL)
1274 		sysctl_ctx_free(&bz->sysctl_ctx);
1275 	kfree(bz, M_DEVBUF);
1276 }
1277 
1278 /* Assume caller holds bounce zone spinlock */
1279 static int
1280 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1281 {
1282 	struct bounce_zone *bz = dmat->bounce_zone;
1283 	int pages;
1284 
1285 	pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1286 	if (!commit && map->pagesneeded > (map->pagesreserved + pages)) {
1287 		bz->reserve_failed++;
1288 		return (map->pagesneeded - (map->pagesreserved + pages));
1289 	}
1290 
1291 	bz->free_bpages -= pages;
1292 
1293 	bz->reserved_bpages += pages;
1294 	KKASSERT(bz->reserved_bpages <= bz->total_bpages);
1295 
1296 	map->pagesreserved += pages;
1297 	pages = map->pagesneeded - map->pagesreserved;
1298 
1299 	return pages;
1300 }
1301 
1302 static void
1303 return_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map)
1304 {
1305 	struct bounce_zone *bz = dmat->bounce_zone;
1306 	int reserved = map->pagesreserved;
1307 	bus_dmamap_t wait_map;
1308 
1309 	map->pagesreserved = 0;
1310 	map->pagesneeded = 0;
1311 
1312 	if (reserved == 0)
1313 		return;
1314 
1315 	BZ_LOCK(bz);
1316 
1317 	bz->free_bpages += reserved;
1318 	KKASSERT(bz->free_bpages <= bz->total_bpages);
1319 
1320 	KKASSERT(bz->reserved_bpages >= reserved);
1321 	bz->reserved_bpages -= reserved;
1322 
1323 	wait_map = get_map_waiting(dmat);
1324 
1325 	BZ_UNLOCK(bz);
1326 
1327 	if (wait_map != NULL)
1328 		add_map_callback(map);
1329 }
1330 
1331 static bus_addr_t
1332 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1333 		bus_size_t size)
1334 {
1335 	struct bounce_zone *bz = dmat->bounce_zone;
1336 	struct bounce_page *bpage;
1337 
1338 	KASSERT(map->pagesneeded > 0, ("map doesn't need any pages"));
1339 	map->pagesneeded--;
1340 
1341 	KASSERT(map->pagesreserved > 0, ("map doesn't reserve any pages"));
1342 	map->pagesreserved--;
1343 
1344 	BZ_LOCK(bz);
1345 
1346 	bpage = STAILQ_FIRST(&bz->bounce_page_list);
1347 	KASSERT(bpage != NULL, ("free page list is empty"));
1348 	STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1349 
1350 	KKASSERT(bz->reserved_bpages > 0);
1351 	bz->reserved_bpages--;
1352 
1353 	bz->active_bpages++;
1354 	KKASSERT(bz->active_bpages <= bz->total_bpages);
1355 
1356 	BZ_UNLOCK(bz);
1357 
1358 	if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1359 		/* Page offset needs to be preserved. */
1360 		bpage->vaddr |= vaddr & PAGE_MASK;
1361 		bpage->busaddr |= vaddr & PAGE_MASK;
1362 	}
1363 
1364 	bpage->datavaddr = vaddr;
1365 	bpage->datacount = size;
1366 	STAILQ_INSERT_TAIL(&map->bpages, bpage, links);
1367 	return bpage->busaddr;
1368 }
1369 
1370 static void
1371 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1372 {
1373 	struct bounce_zone *bz = dmat->bounce_zone;
1374 	bus_dmamap_t map;
1375 
1376 	bpage->datavaddr = 0;
1377 	bpage->datacount = 0;
1378 
1379 	if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1380 		/*
1381 		 * Reset the bounce page to start at offset 0.  Other uses
1382 		 * of this bounce page may need to store a full page of
1383 		 * data and/or assume it starts on a page boundary.
1384 		 */
1385 		bpage->vaddr &= ~PAGE_MASK;
1386 		bpage->busaddr &= ~PAGE_MASK;
1387 	}
1388 
1389 	BZ_LOCK(bz);
1390 
1391 	STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1392 
1393 	bz->free_bpages++;
1394 	KKASSERT(bz->free_bpages <= bz->total_bpages);
1395 
1396 	KKASSERT(bz->active_bpages > 0);
1397 	bz->active_bpages--;
1398 
1399 	map = get_map_waiting(dmat);
1400 
1401 	BZ_UNLOCK(bz);
1402 
1403 	if (map != NULL)
1404 		add_map_callback(map);
1405 }
1406 
1407 /* Assume caller holds bounce zone spinlock */
1408 static bus_dmamap_t
1409 get_map_waiting(bus_dma_tag_t dmat)
1410 {
1411 	struct bounce_zone *bz = dmat->bounce_zone;
1412 	bus_dmamap_t map;
1413 
1414 	map = STAILQ_FIRST(&bz->bounce_map_waitinglist);
1415 	if (map != NULL) {
1416 		if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1417 			STAILQ_REMOVE_HEAD(&bz->bounce_map_waitinglist, links);
1418 			bz->total_deferred++;
1419 		} else {
1420 			map = NULL;
1421 		}
1422 	}
1423 	return map;
1424 }
1425 
1426 static void
1427 add_map_callback(bus_dmamap_t map)
1428 {
1429 	spin_lock(&bounce_map_list_spin);
1430 	STAILQ_INSERT_TAIL(&bounce_map_callbacklist, map, links);
1431 	busdma_swi_pending = 1;
1432 	setsoftvm();
1433 	spin_unlock(&bounce_map_list_spin);
1434 }
1435 
1436 void
1437 busdma_swi(void)
1438 {
1439 	bus_dmamap_t map;
1440 
1441 	spin_lock(&bounce_map_list_spin);
1442 	while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1443 		STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1444 		spin_unlock(&bounce_map_list_spin);
1445 		bus_dmamap_load(map->dmat, map, map->buf, map->buflen,
1446 				map->callback, map->callback_arg, /*flags*/0);
1447 		spin_lock(&bounce_map_list_spin);
1448 	}
1449 	spin_unlock(&bounce_map_list_spin);
1450 }
1451