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