busdma_machdep.c revision 159011
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
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: head/sys/i386/i386/busdma_machdep.c 159011 2006-05-28 18:30:36Z silby $");
29
30#include <sys/param.h>
31#include <sys/kdb.h>
32#include <ddb/ddb.h>
33#include <ddb/db_output.h>
34#include <sys/systm.h>
35#include <sys/malloc.h>
36#include <sys/bus.h>
37#include <sys/interrupt.h>
38#include <sys/kernel.h>
39#include <sys/ktr.h>
40#include <sys/lock.h>
41#include <sys/proc.h>
42#include <sys/mutex.h>
43#include <sys/mbuf.h>
44#include <sys/uio.h>
45#include <sys/sysctl.h>
46
47#include <vm/vm.h>
48#include <vm/vm_page.h>
49#include <vm/vm_map.h>
50
51#include <machine/atomic.h>
52#include <machine/bus.h>
53#include <machine/md_var.h>
54
55#define MAX_BPAGES 512
56
57struct bounce_zone;
58
59struct bus_dma_tag {
60	bus_dma_tag_t	  parent;
61	bus_size_t	  alignment;
62	bus_size_t	  boundary;
63	bus_addr_t	  lowaddr;
64	bus_addr_t	  highaddr;
65	bus_dma_filter_t *filter;
66	void		 *filterarg;
67	bus_size_t	  maxsize;
68	u_int		  nsegments;
69	bus_size_t	  maxsegsz;
70	int		  flags;
71	int		  ref_count;
72	int		  map_count;
73	bus_dma_lock_t	 *lockfunc;
74	void		 *lockfuncarg;
75	bus_dma_segment_t *segments;
76	struct bounce_zone *bounce_zone;
77};
78
79struct bounce_page {
80	vm_offset_t	vaddr;		/* kva of bounce buffer */
81	bus_addr_t	busaddr;	/* Physical address */
82	vm_offset_t	datavaddr;	/* kva of client data */
83	bus_size_t	datacount;	/* client data count */
84	STAILQ_ENTRY(bounce_page) links;
85};
86
87int busdma_swi_pending;
88
89struct bounce_zone {
90	STAILQ_ENTRY(bounce_zone) links;
91	STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
92	int		total_bpages;
93	int		free_bpages;
94	int		reserved_bpages;
95	int		active_bpages;
96	int		total_bounced;
97	int		total_deferred;
98	bus_size_t	alignment;
99	bus_size_t	boundary;
100	bus_addr_t	lowaddr;
101	char		zoneid[8];
102	char		lowaddrid[20];
103	struct sysctl_ctx_list sysctl_tree;
104	struct sysctl_oid *sysctl_tree_top;
105};
106
107static struct mtx bounce_lock;
108static int total_bpages;
109static int busdma_zonecount;
110static STAILQ_HEAD(, bounce_zone) bounce_zone_list;
111
112SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
113SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bpages, 0,
114	   "Total bounce pages");
115
116struct bus_dmamap {
117	struct bp_list	       bpages;
118	int		       pagesneeded;
119	int		       pagesreserved;
120	bus_dma_tag_t	       dmat;
121	void		      *buf;		/* unmapped buffer pointer */
122	bus_size_t	       buflen;		/* unmapped buffer length */
123	bus_dmamap_callback_t *callback;
124	void		      *callback_arg;
125	STAILQ_ENTRY(bus_dmamap) links;
126};
127
128static STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
129static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist;
130static struct bus_dmamap nobounce_dmamap;
131
132static void init_bounce_pages(void *dummy);
133static int alloc_bounce_zone(bus_dma_tag_t dmat);
134static int alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages);
135static int reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
136				int commit);
137static bus_addr_t add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map,
138				   vm_offset_t vaddr, bus_size_t size);
139static void free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage);
140static __inline int run_filter(bus_dma_tag_t dmat, bus_addr_t paddr);
141
142/*
143 * Return true if a match is made.
144 *
145 * To find a match walk the chain of bus_dma_tag_t's looking for 'paddr'.
146 *
147 * If paddr is within the bounds of the dma tag then call the filter callback
148 * to check for a match, if there is no filter callback then assume a match.
149 */
150static __inline int
151run_filter(bus_dma_tag_t dmat, bus_addr_t paddr)
152{
153	int retval;
154
155	retval = 0;
156
157	do {
158		if (((paddr > dmat->lowaddr && paddr <= dmat->highaddr)
159		 || ((paddr & (dmat->alignment - 1)) != 0))
160		 && (dmat->filter == NULL
161		  || (*dmat->filter)(dmat->filterarg, paddr) != 0))
162			retval = 1;
163
164		dmat = dmat->parent;
165	} while (retval == 0 && dmat != NULL);
166	return (retval);
167}
168
169/*
170 * Convenience function for manipulating driver locks from busdma (during
171 * busdma_swi, for example).  Drivers that don't provide their own locks
172 * should specify &Giant to dmat->lockfuncarg.  Drivers that use their own
173 * non-mutex locking scheme don't have to use this at all.
174 */
175void
176busdma_lock_mutex(void *arg, bus_dma_lock_op_t op)
177{
178	struct mtx *dmtx;
179
180	dmtx = (struct mtx *)arg;
181	switch (op) {
182	case BUS_DMA_LOCK:
183		mtx_lock(dmtx);
184		break;
185	case BUS_DMA_UNLOCK:
186		mtx_unlock(dmtx);
187		break;
188	default:
189		panic("Unknown operation 0x%x for busdma_lock_mutex!", op);
190	}
191}
192
193/*
194 * dflt_lock should never get called.  It gets put into the dma tag when
195 * lockfunc == NULL, which is only valid if the maps that are associated
196 * with the tag are meant to never be defered.
197 * XXX Should have a way to identify which driver is responsible here.
198 */
199static void
200dflt_lock(void *arg, bus_dma_lock_op_t op)
201{
202	panic("driver error: busdma dflt_lock called");
203}
204
205#define BUS_DMA_COULD_BOUNCE	BUS_DMA_BUS3
206#define BUS_DMA_MIN_ALLOC_COMP	BUS_DMA_BUS4
207/*
208 * Allocate a device specific dma_tag.
209 */
210int
211bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
212		   bus_size_t boundary, bus_addr_t lowaddr,
213		   bus_addr_t highaddr, bus_dma_filter_t *filter,
214		   void *filterarg, bus_size_t maxsize, int nsegments,
215		   bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
216		   void *lockfuncarg, bus_dma_tag_t *dmat)
217{
218	bus_dma_tag_t newtag;
219	int error = 0;
220
221	/* Basic sanity checking */
222	if (boundary != 0 && boundary < maxsegsz)
223		maxsegsz = boundary;
224
225	/* Return a NULL tag on failure */
226	*dmat = NULL;
227
228	newtag = (bus_dma_tag_t)malloc(sizeof(*newtag), M_DEVBUF,
229	    M_ZERO | M_NOWAIT);
230	if (newtag == NULL) {
231		CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
232		    __func__, newtag, 0, error);
233		return (ENOMEM);
234	}
235
236	newtag->parent = parent;
237	newtag->alignment = alignment;
238	newtag->boundary = boundary;
239	newtag->lowaddr = trunc_page((vm_paddr_t)lowaddr) + (PAGE_SIZE - 1);
240	newtag->highaddr = trunc_page((vm_paddr_t)highaddr) +
241	    (PAGE_SIZE - 1);
242	newtag->filter = filter;
243	newtag->filterarg = filterarg;
244	newtag->maxsize = maxsize;
245	newtag->nsegments = nsegments;
246	newtag->maxsegsz = maxsegsz;
247	newtag->flags = flags;
248	newtag->ref_count = 1; /* Count ourself */
249	newtag->map_count = 0;
250	if (lockfunc != NULL) {
251		newtag->lockfunc = lockfunc;
252		newtag->lockfuncarg = lockfuncarg;
253	} else {
254		newtag->lockfunc = dflt_lock;
255		newtag->lockfuncarg = NULL;
256	}
257	newtag->segments = NULL;
258
259	/* Take into account any restrictions imposed by our parent tag */
260	if (parent != NULL) {
261		newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
262		newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
263		if (newtag->boundary == 0)
264			newtag->boundary = parent->boundary;
265		else if (parent->boundary != 0)
266			newtag->boundary = MIN(parent->boundary,
267					       newtag->boundary);
268		if (newtag->filter == NULL) {
269			/*
270			 * Short circuit looking at our parent directly
271			 * since we have encapsulated all of its information
272			 */
273			newtag->filter = parent->filter;
274			newtag->filterarg = parent->filterarg;
275			newtag->parent = parent->parent;
276		}
277		if (newtag->parent != NULL)
278			atomic_add_int(&parent->ref_count, 1);
279	}
280
281	if (newtag->lowaddr < ptoa((vm_paddr_t)Maxmem)
282	 || newtag->alignment > 1)
283		newtag->flags |= BUS_DMA_COULD_BOUNCE;
284
285	if (((newtag->flags & BUS_DMA_COULD_BOUNCE) != 0) &&
286	    (flags & BUS_DMA_ALLOCNOW) != 0) {
287		struct bounce_zone *bz;
288
289		/* Must bounce */
290
291		if ((error = alloc_bounce_zone(newtag)) != 0) {
292			free(newtag, M_DEVBUF);
293			return (error);
294		}
295		bz = newtag->bounce_zone;
296
297		if (ptoa(bz->total_bpages) < maxsize) {
298			int pages;
299
300			pages = atop(maxsize) - bz->total_bpages;
301
302			/* Add pages to our bounce pool */
303			if (alloc_bounce_pages(newtag, pages) < pages)
304				error = ENOMEM;
305		}
306		/* Performed initial allocation */
307		newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
308	}
309
310	if (error != 0) {
311		free(newtag, M_DEVBUF);
312	} else {
313		*dmat = newtag;
314	}
315	CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
316	    __func__, newtag, (newtag != NULL ? newtag->flags : 0), error);
317	return (error);
318}
319
320int
321bus_dma_tag_destroy(bus_dma_tag_t dmat)
322{
323	bus_dma_tag_t dmat_copy;
324	int error;
325
326	error = 0;
327	dmat_copy = dmat;
328
329	if (dmat != NULL) {
330
331		if (dmat->map_count != 0) {
332			error = EBUSY;
333			goto out;
334		}
335
336		while (dmat != NULL) {
337			bus_dma_tag_t parent;
338
339			parent = dmat->parent;
340			atomic_subtract_int(&dmat->ref_count, 1);
341			if (dmat->ref_count == 0) {
342				if (dmat->segments != NULL)
343					free(dmat->segments, M_DEVBUF);
344				free(dmat, M_DEVBUF);
345				/*
346				 * Last reference count, so
347				 * release our reference
348				 * count on our parent.
349				 */
350				dmat = parent;
351			} else
352				dmat = NULL;
353		}
354	}
355out:
356	CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
357	return (error);
358}
359
360/*
361 * Allocate a handle for mapping from kva/uva/physical
362 * address space into bus device space.
363 */
364int
365bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
366{
367	int error;
368
369	error = 0;
370
371	if (dmat->segments == NULL) {
372		dmat->segments = (bus_dma_segment_t *)malloc(
373		    sizeof(bus_dma_segment_t) * dmat->nsegments, M_DEVBUF,
374		    M_NOWAIT);
375		if (dmat->segments == NULL) {
376			CTR3(KTR_BUSDMA, "%s: tag %p error %d",
377			    __func__, dmat, ENOMEM);
378			return (ENOMEM);
379		}
380	}
381
382	/*
383	 * Bouncing might be required if the driver asks for an active
384	 * exclusion region, a data alignment that is stricter than 1, and/or
385	 * an active address boundary.
386	 */
387	if (dmat->flags & BUS_DMA_COULD_BOUNCE) {
388
389		/* Must bounce */
390		struct bounce_zone *bz;
391		int maxpages;
392
393		if (dmat->bounce_zone == NULL) {
394			if ((error = alloc_bounce_zone(dmat)) != 0)
395				return (error);
396		}
397		bz = dmat->bounce_zone;
398
399		*mapp = (bus_dmamap_t)malloc(sizeof(**mapp), M_DEVBUF,
400					     M_NOWAIT | M_ZERO);
401		if (*mapp == NULL) {
402			CTR3(KTR_BUSDMA, "%s: tag %p error %d",
403			    __func__, dmat, ENOMEM);
404			return (ENOMEM);
405		}
406
407		/* Initialize the new map */
408		STAILQ_INIT(&((*mapp)->bpages));
409
410		/*
411		 * Attempt to add pages to our pool on a per-instance
412		 * basis up to a sane limit.
413		 */
414		if (dmat->alignment > 1)
415			maxpages = MAX_BPAGES;
416		else
417			maxpages = MIN(MAX_BPAGES, Maxmem -atop(dmat->lowaddr));
418		if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0
419		 || (dmat->map_count > 0 && bz->total_bpages < maxpages)) {
420			int pages;
421
422			pages = MAX(atop(dmat->maxsize), 1);
423			pages = MIN(maxpages - bz->total_bpages, pages);
424			pages = MAX(pages, 1);
425			if (alloc_bounce_pages(dmat, pages) < pages)
426				error = ENOMEM;
427
428			if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0) {
429				if (error == 0)
430					dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
431			} else {
432				error = 0;
433			}
434		}
435	} else {
436		*mapp = NULL;
437	}
438	if (error == 0)
439		dmat->map_count++;
440	CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
441	    __func__, dmat, dmat->flags, error);
442	return (error);
443}
444
445/*
446 * Destroy a handle for mapping from kva/uva/physical
447 * address space into bus device space.
448 */
449int
450bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
451{
452	if (map != NULL && map != &nobounce_dmamap) {
453		if (STAILQ_FIRST(&map->bpages) != NULL) {
454			CTR3(KTR_BUSDMA, "%s: tag %p error %d",
455			    __func__, dmat, EBUSY);
456			return (EBUSY);
457		}
458		free(map, M_DEVBUF);
459	}
460	dmat->map_count--;
461	CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
462	return (0);
463}
464
465
466/*
467 * Allocate a piece of memory that can be efficiently mapped into
468 * bus device space based on the constraints lited in the dma tag.
469 * A dmamap to for use with dmamap_load is also allocated.
470 */
471int
472bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
473		 bus_dmamap_t *mapp)
474{
475	int mflags;
476
477	if (flags & BUS_DMA_NOWAIT)
478		mflags = M_NOWAIT;
479	else
480		mflags = M_WAITOK;
481	if (flags & BUS_DMA_ZERO)
482		mflags |= M_ZERO;
483
484	/* If we succeed, no mapping/bouncing will be required */
485	*mapp = NULL;
486
487	if (dmat->segments == NULL) {
488		dmat->segments = (bus_dma_segment_t *)malloc(
489		    sizeof(bus_dma_segment_t) * dmat->nsegments, M_DEVBUF,
490		    M_NOWAIT);
491		if (dmat->segments == NULL) {
492			CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
493			    __func__, dmat, dmat->flags, ENOMEM);
494			return (ENOMEM);
495		}
496	}
497
498	/*
499	 * XXX:
500	 * (dmat->alignment < dmat->maxsize) is just a quick hack; the exact
501	 * alignment guarantees of malloc need to be nailed down, and the
502	 * code below should be rewritten to take that into account.
503	 *
504	 * In the meantime, we'll panic if malloc gets it wrong.
505	 */
506	if ((dmat->maxsize <= PAGE_SIZE) &&
507	   (dmat->alignment < dmat->maxsize) &&
508	    dmat->lowaddr >= ptoa((vm_paddr_t)Maxmem)) {
509		*vaddr = malloc(dmat->maxsize, M_DEVBUF, mflags);
510	} else {
511		/*
512		 * XXX Use Contigmalloc until it is merged into this facility
513		 *     and handles multi-seg allocations.  Nobody is doing
514		 *     multi-seg allocations yet though.
515		 * XXX Certain AGP hardware does.
516		 */
517		*vaddr = contigmalloc(dmat->maxsize, M_DEVBUF, mflags,
518		    0ul, dmat->lowaddr, dmat->alignment? dmat->alignment : 1ul,
519		    dmat->boundary);
520	}
521	if (*vaddr == NULL) {
522		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
523		    __func__, dmat, dmat->flags, ENOMEM);
524		return (ENOMEM);
525	} else if ((uintptr_t)*vaddr & (dmat->alignment - 1)) {
526		panic("bus_dmamem_alloc failed to align memory properly.");
527	}
528	CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
529	    __func__, dmat, dmat->flags, ENOMEM);
530	return (0);
531}
532
533/*
534 * Free a piece of memory and it's allociated dmamap, that was allocated
535 * via bus_dmamem_alloc.  Make the same choice for free/contigfree.
536 */
537void
538bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
539{
540	/*
541	 * dmamem does not need to be bounced, so the map should be
542	 * NULL
543	 */
544	if (map != NULL)
545		panic("bus_dmamem_free: Invalid map freed\n");
546	if ((dmat->maxsize <= PAGE_SIZE) &&
547	   (dmat->alignment < dmat->maxsize) &&
548	    dmat->lowaddr >= ptoa((vm_paddr_t)Maxmem))
549		free(vaddr, M_DEVBUF);
550	else {
551		contigfree(vaddr, dmat->maxsize, M_DEVBUF);
552	}
553	CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat, dmat->flags);
554}
555
556/*
557 * Utility function to load a linear buffer.  lastaddrp holds state
558 * between invocations (for multiple-buffer loads).  segp contains
559 * the starting segment on entrace, and the ending segment on exit.
560 * first indicates if this is the first invocation of this function.
561 */
562static __inline int
563_bus_dmamap_load_buffer(bus_dma_tag_t dmat,
564    			bus_dmamap_t map,
565			void *buf, bus_size_t buflen,
566			pmap_t pmap,
567			int flags,
568			bus_addr_t *lastaddrp,
569			bus_dma_segment_t *segs,
570			int *segp,
571			int first)
572{
573	bus_size_t sgsize;
574	bus_addr_t curaddr, lastaddr, baddr, bmask;
575	vm_offset_t vaddr;
576	bus_addr_t paddr;
577	int needbounce = 0;
578	int seg;
579
580	if (map == NULL)
581		map = &nobounce_dmamap;
582
583	if ((map != &nobounce_dmamap && map->pagesneeded == 0)
584	 && ((dmat->flags & BUS_DMA_COULD_BOUNCE) != 0)) {
585		vm_offset_t	vendaddr;
586
587		CTR4(KTR_BUSDMA, "lowaddr= %d Maxmem= %d, boundary= %d, "
588		    "alignment= %d", dmat->lowaddr, ptoa((vm_paddr_t)Maxmem),
589		    dmat->boundary, dmat->alignment);
590		CTR3(KTR_BUSDMA, "map= %p, nobouncemap= %p, pagesneeded= %d",
591		    map, &nobounce_dmamap, map->pagesneeded);
592		/*
593		 * Count the number of bounce pages
594		 * needed in order to complete this transfer
595		 */
596		vaddr = trunc_page((vm_offset_t)buf);
597		vendaddr = (vm_offset_t)buf + buflen;
598
599		while (vaddr < vendaddr) {
600			paddr = pmap_kextract(vaddr);
601			if (run_filter(dmat, paddr) != 0) {
602				needbounce = 1;
603				map->pagesneeded++;
604			}
605			vaddr += PAGE_SIZE;
606		}
607		CTR1(KTR_BUSDMA, "pagesneeded= %d\n", map->pagesneeded);
608	}
609
610	/* Reserve Necessary Bounce Pages */
611	if (map->pagesneeded != 0) {
612		mtx_lock(&bounce_lock);
613		if (flags & BUS_DMA_NOWAIT) {
614			if (reserve_bounce_pages(dmat, map, 0) != 0) {
615				mtx_unlock(&bounce_lock);
616				return (ENOMEM);
617			}
618		} else {
619			if (reserve_bounce_pages(dmat, map, 1) != 0) {
620				/* Queue us for resources */
621				map->dmat = dmat;
622				map->buf = buf;
623				map->buflen = buflen;
624				STAILQ_INSERT_TAIL(&bounce_map_waitinglist,
625				    map, links);
626				mtx_unlock(&bounce_lock);
627				return (EINPROGRESS);
628			}
629		}
630		mtx_unlock(&bounce_lock);
631	}
632
633	vaddr = (vm_offset_t)buf;
634	lastaddr = *lastaddrp;
635	bmask = ~(dmat->boundary - 1);
636
637	for (seg = *segp; buflen > 0 ; ) {
638		/*
639		 * Get the physical address for this segment.
640		 */
641		if (pmap)
642			curaddr = pmap_extract(pmap, vaddr);
643		else
644			curaddr = pmap_kextract(vaddr);
645
646		/*
647		 * Compute the segment size, and adjust counts.
648		 */
649		sgsize = PAGE_SIZE - ((u_long)curaddr & PAGE_MASK);
650		if (buflen < sgsize)
651			sgsize = buflen;
652
653		/*
654		 * Make sure we don't cross any boundaries.
655		 */
656		if (dmat->boundary > 0) {
657			baddr = (curaddr + dmat->boundary) & bmask;
658			if (sgsize > (baddr - curaddr))
659				sgsize = (baddr - curaddr);
660		}
661
662		if (map->pagesneeded != 0 && run_filter(dmat, curaddr))
663			curaddr = add_bounce_page(dmat, map, vaddr, sgsize);
664
665		/*
666		 * Insert chunk into a segment, coalescing with
667		 * previous segment if possible.
668		 */
669		if (first) {
670			segs[seg].ds_addr = curaddr;
671			segs[seg].ds_len = sgsize;
672			first = 0;
673		} else {
674			if (needbounce == 0 && curaddr == lastaddr &&
675			    (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
676			    (dmat->boundary == 0 ||
677			     (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
678				segs[seg].ds_len += sgsize;
679			else {
680				if (++seg >= dmat->nsegments)
681					break;
682				segs[seg].ds_addr = curaddr;
683				segs[seg].ds_len = sgsize;
684			}
685		}
686
687		lastaddr = curaddr + sgsize;
688		vaddr += sgsize;
689		buflen -= sgsize;
690	}
691
692	*segp = seg;
693	*lastaddrp = lastaddr;
694
695	/*
696	 * Did we fit?
697	 */
698	return (buflen != 0 ? EFBIG : 0); /* XXX better return value here? */
699}
700
701/*
702 * Map the buffer buf into bus space using the dmamap map.
703 */
704int
705bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
706		bus_size_t buflen, bus_dmamap_callback_t *callback,
707		void *callback_arg, int flags)
708{
709	bus_addr_t		lastaddr = 0;
710	int			error, nsegs = 0;
711
712	if (map != NULL) {
713		flags |= BUS_DMA_WAITOK;
714		map->callback = callback;
715		map->callback_arg = callback_arg;
716	}
717
718	error = _bus_dmamap_load_buffer(dmat, map, buf, buflen, NULL, flags,
719	     &lastaddr, dmat->segments, &nsegs, 1);
720
721	CTR5(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d nsegs %d",
722	    __func__, dmat, dmat->flags, error, nsegs + 1);
723
724	if (error == EINPROGRESS) {
725		return (error);
726	}
727
728	if (error)
729		(*callback)(callback_arg, dmat->segments, 0, error);
730	else
731		(*callback)(callback_arg, dmat->segments, nsegs + 1, 0);
732
733	/*
734	 * Return ENOMEM to the caller so that it can pass it up the stack.
735	 * This error only happens when NOWAIT is set, so deferal is disabled.
736	 */
737	if (error == ENOMEM)
738		return (error);
739
740	return (0);
741}
742
743
744/*
745 * Like _bus_dmamap_load(), but for mbufs.
746 */
747int
748bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map,
749		     struct mbuf *m0,
750		     bus_dmamap_callback2_t *callback, void *callback_arg,
751		     int flags)
752{
753	int nsegs, error;
754
755	M_ASSERTPKTHDR(m0);
756
757	flags |= BUS_DMA_NOWAIT;
758	nsegs = 0;
759	error = 0;
760	if (m0->m_pkthdr.len <= dmat->maxsize) {
761		int first = 1;
762		bus_addr_t lastaddr = 0;
763		struct mbuf *m;
764
765		for (m = m0; m != NULL && error == 0; m = m->m_next) {
766			if (m->m_len > 0) {
767				error = _bus_dmamap_load_buffer(dmat, map,
768						m->m_data, m->m_len,
769						NULL, flags, &lastaddr,
770						dmat->segments, &nsegs, first);
771				first = 0;
772			}
773		}
774	} else {
775		error = EINVAL;
776	}
777
778	if (error) {
779		/* force "no valid mappings" in callback */
780		(*callback)(callback_arg, dmat->segments, 0, 0, error);
781	} else {
782		(*callback)(callback_arg, dmat->segments,
783			    nsegs+1, m0->m_pkthdr.len, error);
784	}
785	CTR5(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d nsegs %d",
786	    __func__, dmat, dmat->flags, error, nsegs + 1);
787	return (error);
788}
789
790int
791bus_dmamap_load_mbuf_sg(bus_dma_tag_t dmat, bus_dmamap_t map,
792			struct mbuf *m0, bus_dma_segment_t *segs, int *nsegs,
793			int flags)
794{
795	int error;
796
797	M_ASSERTPKTHDR(m0);
798
799	flags |= BUS_DMA_NOWAIT;
800	*nsegs = 0;
801	error = 0;
802	if (m0->m_pkthdr.len <= dmat->maxsize) {
803		int first = 1;
804		bus_addr_t lastaddr = 0;
805		struct mbuf *m;
806
807		for (m = m0; m != NULL && error == 0; m = m->m_next) {
808			if (m->m_len > 0) {
809				error = _bus_dmamap_load_buffer(dmat, map,
810						m->m_data, m->m_len,
811						NULL, flags, &lastaddr,
812						segs, nsegs, first);
813				first = 0;
814			}
815		}
816	} else {
817		error = EINVAL;
818	}
819
820	/* XXX FIXME: Having to increment nsegs is really annoying */
821	++*nsegs;
822	CTR5(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d nsegs %d",
823	    __func__, dmat, dmat->flags, error, *nsegs);
824	return (error);
825}
826
827/*
828 * Like _bus_dmamap_load(), but for uios.
829 */
830int
831bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
832		    struct uio *uio,
833		    bus_dmamap_callback2_t *callback, void *callback_arg,
834		    int flags)
835{
836	bus_addr_t lastaddr;
837	int nsegs, error, first, i;
838	bus_size_t resid;
839	struct iovec *iov;
840	pmap_t pmap;
841
842	flags |= BUS_DMA_NOWAIT;
843	resid = uio->uio_resid;
844	iov = uio->uio_iov;
845
846	if (uio->uio_segflg == UIO_USERSPACE) {
847		KASSERT(uio->uio_td != NULL,
848			("bus_dmamap_load_uio: USERSPACE but no proc"));
849		pmap = vmspace_pmap(uio->uio_td->td_proc->p_vmspace);
850	} else
851		pmap = NULL;
852
853	nsegs = 0;
854	error = 0;
855	first = 1;
856	for (i = 0; i < uio->uio_iovcnt && resid != 0 && !error; i++) {
857		/*
858		 * Now at the first iovec to load.  Load each iovec
859		 * until we have exhausted the residual count.
860		 */
861		bus_size_t minlen =
862			resid < iov[i].iov_len ? resid : iov[i].iov_len;
863		caddr_t addr = (caddr_t) iov[i].iov_base;
864
865		if (minlen > 0) {
866			error = _bus_dmamap_load_buffer(dmat, map,
867					addr, minlen, pmap, flags, &lastaddr,
868					dmat->segments, &nsegs, first);
869			first = 0;
870
871			resid -= minlen;
872		}
873	}
874
875	if (error) {
876		/* force "no valid mappings" in callback */
877		(*callback)(callback_arg, dmat->segments, 0, 0, error);
878	} else {
879		(*callback)(callback_arg, dmat->segments,
880			    nsegs+1, uio->uio_resid, error);
881	}
882	CTR5(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d nsegs %d",
883	    __func__, dmat, dmat->flags, error, nsegs + 1);
884	return (error);
885}
886
887/*
888 * Release the mapping held by map.
889 */
890void
891_bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
892{
893	struct bounce_page *bpage;
894
895	while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
896		STAILQ_REMOVE_HEAD(&map->bpages, links);
897		free_bounce_page(dmat, bpage);
898	}
899}
900
901void
902_bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
903{
904	struct bounce_page *bpage;
905
906	if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
907		/*
908		 * Handle data bouncing.  We might also
909		 * want to add support for invalidating
910		 * the caches on broken hardware
911		 */
912		dmat->bounce_zone->total_bounced++;
913		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
914		    "performing bounce", __func__, op, dmat, dmat->flags);
915
916		if (op & BUS_DMASYNC_PREWRITE) {
917			while (bpage != NULL) {
918				bcopy((void *)bpage->datavaddr,
919				      (void *)bpage->vaddr,
920				      bpage->datacount);
921				bpage = STAILQ_NEXT(bpage, links);
922			}
923		}
924
925		if (op & BUS_DMASYNC_POSTREAD) {
926			while (bpage != NULL) {
927				bcopy((void *)bpage->vaddr,
928				      (void *)bpage->datavaddr,
929				      bpage->datacount);
930				bpage = STAILQ_NEXT(bpage, links);
931			}
932		}
933	}
934}
935
936static void
937init_bounce_pages(void *dummy __unused)
938{
939
940	total_bpages = 0;
941	STAILQ_INIT(&bounce_zone_list);
942	STAILQ_INIT(&bounce_map_waitinglist);
943	STAILQ_INIT(&bounce_map_callbacklist);
944	mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
945}
946SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
947
948static struct sysctl_ctx_list *
949busdma_sysctl_tree(struct bounce_zone *bz)
950{
951	return (&bz->sysctl_tree);
952}
953
954static struct sysctl_oid *
955busdma_sysctl_tree_top(struct bounce_zone *bz)
956{
957	return (bz->sysctl_tree_top);
958}
959
960static int
961alloc_bounce_zone(bus_dma_tag_t dmat)
962{
963	struct bounce_zone *bz;
964
965	/* Check to see if we already have a suitable zone */
966	STAILQ_FOREACH(bz, &bounce_zone_list, links) {
967		if ((dmat->alignment <= bz->alignment)
968		 && (dmat->boundary <= bz->boundary)
969		 && (dmat->lowaddr >= bz->lowaddr)) {
970			dmat->bounce_zone = bz;
971			return (0);
972		}
973	}
974
975	if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_DEVBUF,
976	    M_NOWAIT | M_ZERO)) == NULL)
977		return (ENOMEM);
978
979	STAILQ_INIT(&bz->bounce_page_list);
980	bz->free_bpages = 0;
981	bz->reserved_bpages = 0;
982	bz->active_bpages = 0;
983	bz->lowaddr = dmat->lowaddr;
984	bz->alignment = dmat->alignment;
985	bz->boundary = dmat->boundary;
986	snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
987	busdma_zonecount++;
988	snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
989	STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
990	dmat->bounce_zone = bz;
991
992	sysctl_ctx_init(&bz->sysctl_tree);
993	bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
994	    SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
995	    CTLFLAG_RD, 0, "");
996	if (bz->sysctl_tree_top == NULL) {
997		sysctl_ctx_free(&bz->sysctl_tree);
998		return (0);	/* XXX error code? */
999	}
1000
1001	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1002	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1003	    "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1004	    "Total bounce pages");
1005	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1006	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1007	    "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1008	    "Free bounce pages");
1009	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1010	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1011	    "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1012	    "Reserved bounce pages");
1013	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1014	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1015	    "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1016	    "Active bounce pages");
1017	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1018	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1019	    "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1020	    "Total bounce requests");
1021	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1022	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1023	    "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1024	    "Total bounce requests that were deferred");
1025	SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1026	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1027	    "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1028	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1029	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1030	    "alignment", CTLFLAG_RD, &bz->alignment, 0, "");
1031	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1032	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1033	    "boundary", CTLFLAG_RD, &bz->boundary, 0, "");
1034
1035	return (0);
1036}
1037
1038static int
1039alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1040{
1041	struct bounce_zone *bz;
1042	int count;
1043
1044	bz = dmat->bounce_zone;
1045	count = 0;
1046	while (numpages > 0) {
1047		struct bounce_page *bpage;
1048
1049		bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_DEVBUF,
1050						     M_NOWAIT | M_ZERO);
1051
1052		if (bpage == NULL)
1053			break;
1054		bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
1055							 M_NOWAIT, 0ul,
1056							 bz->lowaddr,
1057							 PAGE_SIZE,
1058							 bz->boundary);
1059		if (bpage->vaddr == 0) {
1060			free(bpage, M_DEVBUF);
1061			break;
1062		}
1063		bpage->busaddr = pmap_kextract(bpage->vaddr);
1064		mtx_lock(&bounce_lock);
1065		STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1066		total_bpages++;
1067		bz->total_bpages++;
1068		bz->free_bpages++;
1069		mtx_unlock(&bounce_lock);
1070		count++;
1071		numpages--;
1072	}
1073	return (count);
1074}
1075
1076static int
1077reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1078{
1079	struct bounce_zone *bz;
1080	int pages;
1081
1082	mtx_assert(&bounce_lock, MA_OWNED);
1083	bz = dmat->bounce_zone;
1084	pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1085	if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1086		return (map->pagesneeded - (map->pagesreserved + pages));
1087	bz->free_bpages -= pages;
1088	bz->reserved_bpages += pages;
1089	map->pagesreserved += pages;
1090	pages = map->pagesneeded - map->pagesreserved;
1091
1092	return (pages);
1093}
1094
1095static bus_addr_t
1096add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1097		bus_size_t size)
1098{
1099	struct bounce_zone *bz;
1100	struct bounce_page *bpage;
1101
1102	KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1103	KASSERT(map != NULL && map != &nobounce_dmamap,
1104	    ("add_bounce_page: bad map %p", map));
1105
1106	bz = dmat->bounce_zone;
1107	if (map->pagesneeded == 0)
1108		panic("add_bounce_page: map doesn't need any pages");
1109	map->pagesneeded--;
1110
1111	if (map->pagesreserved == 0)
1112		panic("add_bounce_page: map doesn't need any pages");
1113	map->pagesreserved--;
1114
1115	mtx_lock(&bounce_lock);
1116	bpage = STAILQ_FIRST(&bz->bounce_page_list);
1117	if (bpage == NULL)
1118		panic("add_bounce_page: free page list is empty");
1119
1120	STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1121	bz->reserved_bpages--;
1122	bz->active_bpages++;
1123	mtx_unlock(&bounce_lock);
1124
1125	bpage->datavaddr = vaddr;
1126	bpage->datacount = size;
1127	STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1128	return (bpage->busaddr);
1129}
1130
1131static void
1132free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1133{
1134	struct bus_dmamap *map;
1135	struct bounce_zone *bz;
1136
1137	bz = dmat->bounce_zone;
1138	bpage->datavaddr = 0;
1139	bpage->datacount = 0;
1140
1141	mtx_lock(&bounce_lock);
1142	STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1143	bz->free_bpages++;
1144	bz->active_bpages--;
1145	if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1146		if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1147			STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1148			STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1149					   map, links);
1150			busdma_swi_pending = 1;
1151			bz->total_deferred++;
1152			swi_sched(vm_ih, 0);
1153		}
1154	}
1155	mtx_unlock(&bounce_lock);
1156}
1157
1158void
1159busdma_swi(void)
1160{
1161	bus_dma_tag_t dmat;
1162	struct bus_dmamap *map;
1163
1164	mtx_lock(&bounce_lock);
1165	while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1166		STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1167		mtx_unlock(&bounce_lock);
1168		dmat = map->dmat;
1169		(dmat->lockfunc)(dmat->lockfuncarg, BUS_DMA_LOCK);
1170		bus_dmamap_load(map->dmat, map, map->buf, map->buflen,
1171				map->callback, map->callback_arg, /*flags*/0);
1172		(dmat->lockfunc)(dmat->lockfuncarg, BUS_DMA_UNLOCK);
1173		mtx_lock(&bounce_lock);
1174	}
1175	mtx_unlock(&bounce_lock);
1176}
1177