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