busdma_machdep-v6.c revision 254061
1/*-
2 * Copyright (c) 2012 Ian Lepore
3 * Copyright (c) 2010 Mark Tinguely
4 * Copyright (c) 2004 Olivier Houchard
5 * Copyright (c) 2002 Peter Grehan
6 * Copyright (c) 1997, 1998 Justin T. Gibbs.
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions, and the following disclaimer,
14 *    without modification, immediately at the beginning of the file.
15 * 2. The name of the author may not be used to endorse or promote products
16 *    derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
22 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * SUCH DAMAGE.
29 *
30 *  From i386/busdma_machdep.c 191438 2009-04-23 20:24:19Z jhb
31 */
32
33#include <sys/cdefs.h>
34__FBSDID("$FreeBSD: head/sys/arm/arm/busdma_machdep-v6.c 254061 2013-08-07 15:44:58Z cognet $");
35
36#define _ARM32_BUS_DMA_PRIVATE
37#include <sys/param.h>
38#include <sys/kdb.h>
39#include <ddb/ddb.h>
40#include <ddb/db_output.h>
41#include <sys/systm.h>
42#include <sys/malloc.h>
43#include <sys/bus.h>
44#include <sys/busdma_bufalloc.h>
45#include <sys/interrupt.h>
46#include <sys/kernel.h>
47#include <sys/ktr.h>
48#include <sys/lock.h>
49#include <sys/memdesc.h>
50#include <sys/proc.h>
51#include <sys/mutex.h>
52#include <sys/sysctl.h>
53#include <sys/uio.h>
54
55#include <vm/vm.h>
56#include <vm/vm_page.h>
57#include <vm/vm_map.h>
58#include <vm/vm_extern.h>
59#include <vm/vm_kern.h>
60
61#include <machine/atomic.h>
62#include <machine/bus.h>
63#include <machine/cpufunc.h>
64#include <machine/md_var.h>
65
66#define MAX_BPAGES 64
67#define BUS_DMA_COULD_BOUNCE	BUS_DMA_BUS3
68#define BUS_DMA_MIN_ALLOC_COMP	BUS_DMA_BUS4
69
70struct bounce_zone;
71
72struct bus_dma_tag {
73	bus_dma_tag_t	  parent;
74	bus_size_t	  alignment;
75	bus_size_t	  boundary;
76	bus_addr_t	  lowaddr;
77	bus_addr_t	  highaddr;
78	bus_dma_filter_t *filter;
79	void		 *filterarg;
80	bus_size_t	  maxsize;
81	u_int		  nsegments;
82	bus_size_t	  maxsegsz;
83	int		  flags;
84	int		  ref_count;
85	int		  map_count;
86	bus_dma_lock_t	 *lockfunc;
87	void		 *lockfuncarg;
88	struct bounce_zone *bounce_zone;
89	/*
90	 * DMA range for this tag.  If the page doesn't fall within
91	 * one of these ranges, an error is returned.  The caller
92	 * may then decide what to do with the transfer.  If the
93	 * range pointer is NULL, it is ignored.
94	 */
95	struct arm32_dma_range	*ranges;
96	int			_nranges;
97	/*
98	 * Most tags need one or two segments, and can use the local tagsegs
99	 * array.  For tags with a larger limit, we'll allocate a bigger array
100	 * on first use.
101	 */
102	bus_dma_segment_t	*segments;
103	bus_dma_segment_t	tagsegs[2];
104
105
106};
107
108struct bounce_page {
109	vm_offset_t	vaddr;		/* kva of bounce buffer */
110	bus_addr_t	busaddr;	/* Physical address */
111	vm_offset_t	datavaddr;	/* kva of client data */
112	bus_addr_t	dataaddr;	/* client physical address */
113	bus_size_t	datacount;	/* client data count */
114	STAILQ_ENTRY(bounce_page) links;
115};
116
117struct sync_list {
118	vm_offset_t	vaddr;		/* kva of bounce buffer */
119	bus_addr_t	busaddr;	/* Physical address */
120	bus_size_t	datacount;	/* client data count */
121};
122
123int busdma_swi_pending;
124
125struct bounce_zone {
126	STAILQ_ENTRY(bounce_zone) links;
127	STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
128	int		total_bpages;
129	int		free_bpages;
130	int		reserved_bpages;
131	int		active_bpages;
132	int		total_bounced;
133	int		total_deferred;
134	int		map_count;
135	bus_size_t	alignment;
136	bus_addr_t	lowaddr;
137	char		zoneid[8];
138	char		lowaddrid[20];
139	struct sysctl_ctx_list sysctl_tree;
140	struct sysctl_oid *sysctl_tree_top;
141};
142
143static struct mtx bounce_lock;
144static int total_bpages;
145static int busdma_zonecount;
146static STAILQ_HEAD(, bounce_zone) bounce_zone_list;
147
148SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
149SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bpages, 0,
150	   "Total bounce pages");
151
152struct bus_dmamap {
153	struct bp_list	       bpages;
154	int		       pagesneeded;
155	int		       pagesreserved;
156	bus_dma_tag_t	       dmat;
157	struct memdesc	       mem;
158	pmap_t		       pmap;
159	bus_dmamap_callback_t *callback;
160	void		      *callback_arg;
161	int		      flags;
162#define DMAMAP_COHERENT		(1 << 0)
163	STAILQ_ENTRY(bus_dmamap) links;
164	int		       sync_count;
165	struct sync_list       slist[];
166};
167
168static STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
169static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist;
170
171static void init_bounce_pages(void *dummy);
172static int alloc_bounce_zone(bus_dma_tag_t dmat);
173static int alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages);
174static int reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
175				int commit);
176static bus_addr_t add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map,
177				  vm_offset_t vaddr, bus_addr_t addr,
178				  bus_size_t size);
179static void free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage);
180int run_filter(bus_dma_tag_t dmat, bus_addr_t paddr, bus_size_t size, int coherent);
181static void _bus_dmamap_count_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
182    void *buf, bus_size_t buflen, int flags);
183static void _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map,
184    vm_paddr_t buf, bus_size_t buflen, int flags);
185static int _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
186    int flags);
187
188static busdma_bufalloc_t coherent_allocator;	/* Cache of coherent buffers */
189static busdma_bufalloc_t standard_allocator;	/* Cache of standard buffers */
190static void
191busdma_init(void *dummy)
192{
193	int uma_flags;
194
195	uma_flags = 0;
196
197	/* Create a cache of buffers in standard (cacheable) memory. */
198	standard_allocator = busdma_bufalloc_create("buffer",
199	    arm_dcache_align,	/* minimum_alignment */
200	    NULL,		/* uma_alloc func */
201	    NULL,		/* uma_free func */
202	    uma_flags);		/* uma_zcreate_flags */
203
204#ifdef INVARIANTS
205	/*
206	 * Force UMA zone to allocate service structures like
207	 * slabs using own allocator. uma_debug code performs
208	 * atomic ops on uma_slab_t fields and safety of this
209	 * operation is not guaranteed for write-back caches
210	 */
211	uma_flags = UMA_ZONE_OFFPAGE;
212#endif
213	/*
214	 * Create a cache of buffers in uncacheable memory, to implement the
215	 * BUS_DMA_COHERENT (and potentially BUS_DMA_NOCACHE) flag.
216	 */
217	coherent_allocator = busdma_bufalloc_create("coherent",
218	    arm_dcache_align,	/* minimum_alignment */
219	    busdma_bufalloc_alloc_uncacheable,
220	    busdma_bufalloc_free_uncacheable,
221	    uma_flags);	/* uma_zcreate_flags */
222}
223
224/*
225 * This init historically used SI_SUB_VM, but now the init code requires
226 * malloc(9) using M_DEVBUF memory, which is set up later than SI_SUB_VM, by
227 * SI_SUB_KMEM and SI_ORDER_SECOND, so we'll go right after that by using
228 * SI_SUB_KMEM and SI_ORDER_THIRD.
229 */
230SYSINIT(busdma, SI_SUB_KMEM, SI_ORDER_THIRD, busdma_init, NULL);
231
232static __inline int
233_bus_dma_can_bounce(vm_offset_t lowaddr, vm_offset_t highaddr)
234{
235	int i;
236	for (i = 0; phys_avail[i] && phys_avail[i + 1]; i += 2) {
237		if ((lowaddr >= phys_avail[i] && lowaddr <= phys_avail[i + 1])
238		    || (lowaddr < phys_avail[i] &&
239		    highaddr > phys_avail[i]))
240			return (1);
241	}
242	return (0);
243}
244
245static __inline struct arm32_dma_range *
246_bus_dma_inrange(struct arm32_dma_range *ranges, int nranges,
247    bus_addr_t curaddr)
248{
249	struct arm32_dma_range *dr;
250	int i;
251
252	for (i = 0, dr = ranges; i < nranges; i++, dr++) {
253		if (curaddr >= dr->dr_sysbase &&
254		    round_page(curaddr) <= (dr->dr_sysbase + dr->dr_len))
255			return (dr);
256	}
257
258	return (NULL);
259}
260
261/*
262 * Return true if a match is made.
263 *
264 * To find a match walk the chain of bus_dma_tag_t's looking for 'paddr'.
265 *
266 * If paddr is within the bounds of the dma tag then call the filter callback
267 * to check for a match, if there is no filter callback then assume a match.
268 */
269int
270run_filter(bus_dma_tag_t dmat, bus_addr_t paddr, bus_size_t size, int coherent)
271{
272	int retval;
273
274	retval = 0;
275
276	do {
277		if (((paddr > dmat->lowaddr && paddr <= dmat->highaddr)
278		 || ((paddr & (dmat->alignment - 1)) != 0) ||
279		 (!coherent && (size & arm_dcache_align_mask)) ||
280		 (!coherent && (paddr & arm_dcache_align_mask)))
281		 && (dmat->filter == NULL
282		  || (*dmat->filter)(dmat->filterarg, paddr) != 0))
283			retval = 1;
284
285		dmat = dmat->parent;
286	} while (retval == 0 && dmat != NULL);
287	return (retval);
288}
289
290/*
291 * Convenience function for manipulating driver locks from busdma (during
292 * busdma_swi, for example).  Drivers that don't provide their own locks
293 * should specify &Giant to dmat->lockfuncarg.  Drivers that use their own
294 * non-mutex locking scheme don't have to use this at all.
295 */
296void
297busdma_lock_mutex(void *arg, bus_dma_lock_op_t op)
298{
299	struct mtx *dmtx;
300
301	dmtx = (struct mtx *)arg;
302	switch (op) {
303	case BUS_DMA_LOCK:
304		mtx_lock(dmtx);
305		break;
306	case BUS_DMA_UNLOCK:
307		mtx_unlock(dmtx);
308		break;
309	default:
310		panic("Unknown operation 0x%x for busdma_lock_mutex!", op);
311	}
312}
313
314/*
315 * dflt_lock should never get called.  It gets put into the dma tag when
316 * lockfunc == NULL, which is only valid if the maps that are associated
317 * with the tag are meant to never be defered.
318 * XXX Should have a way to identify which driver is responsible here.
319 */
320static void
321dflt_lock(void *arg, bus_dma_lock_op_t op)
322{
323	panic("driver error: busdma dflt_lock called");
324}
325
326/*
327 * Allocate a device specific dma_tag.
328 */
329int
330bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
331		   bus_size_t boundary, bus_addr_t lowaddr,
332		   bus_addr_t highaddr, bus_dma_filter_t *filter,
333		   void *filterarg, bus_size_t maxsize, int nsegments,
334		   bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
335		   void *lockfuncarg, bus_dma_tag_t *dmat)
336{
337	bus_dma_tag_t newtag;
338	int error = 0;
339
340#if 0
341	if (!parent)
342		parent = arm_root_dma_tag;
343#endif
344
345	/* Basic sanity checking */
346	if (boundary != 0 && boundary < maxsegsz)
347		maxsegsz = boundary;
348
349	/* Return a NULL tag on failure */
350	*dmat = NULL;
351
352	if (maxsegsz == 0) {
353		return (EINVAL);
354	}
355
356	newtag = (bus_dma_tag_t)malloc(sizeof(*newtag), M_DEVBUF,
357	    M_ZERO | M_NOWAIT);
358	if (newtag == NULL) {
359		CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
360		    __func__, newtag, 0, error);
361		return (ENOMEM);
362	}
363
364	newtag->parent = parent;
365	newtag->alignment = alignment;
366	newtag->boundary = boundary;
367	newtag->lowaddr = trunc_page((vm_paddr_t)lowaddr) + (PAGE_SIZE - 1);
368	newtag->highaddr = trunc_page((vm_paddr_t)highaddr) +
369	    (PAGE_SIZE - 1);
370	newtag->filter = filter;
371	newtag->filterarg = filterarg;
372	newtag->maxsize = maxsize;
373	newtag->nsegments = nsegments;
374	newtag->maxsegsz = maxsegsz;
375	newtag->flags = flags;
376	newtag->ref_count = 1; /* Count ourself */
377	newtag->map_count = 0;
378	newtag->ranges = bus_dma_get_range();
379	newtag->_nranges = bus_dma_get_range_nb();
380	if (lockfunc != NULL) {
381		newtag->lockfunc = lockfunc;
382		newtag->lockfuncarg = lockfuncarg;
383	} else {
384		newtag->lockfunc = dflt_lock;
385		newtag->lockfuncarg = NULL;
386	}
387	/*
388	 * If all the segments we need fit into the local tagsegs array, set the
389	 * pointer now.  Otherwise NULL the pointer and an array of segments
390	 * will be allocated later, on first use.  We don't pre-allocate now
391	 * because some tags exist just to pass contraints to children in the
392	 * device hierarchy, and they tend to use BUS_SPACE_UNRESTRICTED and we
393	 * sure don't want to try to allocate an array for that.
394	 */
395	if (newtag->nsegments <= nitems(newtag->tagsegs))
396		newtag->segments = newtag->tagsegs;
397	else
398		newtag->segments = NULL;
399
400	/* Take into account any restrictions imposed by our parent tag */
401	if (parent != NULL) {
402		newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
403		newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
404		if (newtag->boundary == 0)
405			newtag->boundary = parent->boundary;
406		else if (parent->boundary != 0)
407			newtag->boundary = MIN(parent->boundary,
408					       newtag->boundary);
409		if ((newtag->filter != NULL) ||
410		    ((parent->flags & BUS_DMA_COULD_BOUNCE) != 0))
411			newtag->flags |= BUS_DMA_COULD_BOUNCE;
412		if (newtag->filter == NULL) {
413			/*
414			 * Short circuit looking at our parent directly
415			 * since we have encapsulated all of its information
416			 */
417			newtag->filter = parent->filter;
418			newtag->filterarg = parent->filterarg;
419			newtag->parent = parent->parent;
420		}
421		if (newtag->parent != NULL)
422			atomic_add_int(&parent->ref_count, 1);
423	}
424
425	if (_bus_dma_can_bounce(newtag->lowaddr, newtag->highaddr)
426	 || newtag->alignment > 1)
427		newtag->flags |= BUS_DMA_COULD_BOUNCE;
428
429	if ((flags & BUS_DMA_ALLOCNOW) != 0) {
430		struct bounce_zone *bz;
431
432		/* Must bounce */
433
434		if ((error = alloc_bounce_zone(newtag)) != 0) {
435			free(newtag, M_DEVBUF);
436			return (error);
437		}
438		bz = newtag->bounce_zone;
439
440		if (ptoa(bz->total_bpages) < maxsize) {
441			int pages;
442
443			pages = atop(maxsize) - bz->total_bpages;
444
445			/* Add pages to our bounce pool */
446			if (alloc_bounce_pages(newtag, pages) < pages)
447				error = ENOMEM;
448		}
449		/* Performed initial allocation */
450		newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
451	} else
452		newtag->bounce_zone = NULL;
453
454	if (error != 0) {
455		free(newtag, M_DEVBUF);
456	} else {
457		*dmat = newtag;
458	}
459	CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
460	    __func__, newtag, (newtag != NULL ? newtag->flags : 0), error);
461	return (error);
462}
463
464int
465bus_dma_tag_destroy(bus_dma_tag_t dmat)
466{
467	bus_dma_tag_t dmat_copy;
468	int error;
469
470	error = 0;
471	dmat_copy = dmat;
472
473	if (dmat != NULL) {
474
475		if (dmat->map_count != 0) {
476			error = EBUSY;
477			goto out;
478		}
479
480		while (dmat != NULL) {
481			bus_dma_tag_t parent;
482
483			parent = dmat->parent;
484			atomic_subtract_int(&dmat->ref_count, 1);
485			if (dmat->ref_count == 0) {
486				if (dmat->segments != NULL &&
487				    dmat->segments != dmat->tagsegs)
488					free(dmat->segments, M_DEVBUF);
489				free(dmat, M_DEVBUF);
490				/*
491				 * Last reference count, so
492				 * release our reference
493				 * count on our parent.
494				 */
495				dmat = parent;
496			} else
497				dmat = NULL;
498		}
499	}
500out:
501	CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
502	return (error);
503}
504
505static int allocate_bz_and_pages(bus_dma_tag_t dmat, bus_dmamap_t mapp)
506{
507        struct bounce_zone *bz;
508	int maxpages;
509	int error;
510
511	if (dmat->bounce_zone == NULL)
512		if ((error = alloc_bounce_zone(dmat)) != 0)
513			return (error);
514	bz = dmat->bounce_zone;
515	/* Initialize the new map */
516	STAILQ_INIT(&(mapp->bpages));
517
518	/*
519	 * Attempt to add pages to our pool on a per-instance
520	 * basis up to a sane limit.
521	 */
522	maxpages = MAX_BPAGES;
523	if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0
524	    || (bz->map_count > 0 && bz->total_bpages < maxpages)) {
525		int pages;
526
527		pages = MAX(atop(dmat->maxsize), 1);
528		pages = MIN(maxpages - bz->total_bpages, pages);
529		pages = MAX(pages, 1);
530		if (alloc_bounce_pages(dmat, pages) < pages)
531			return (ENOMEM);
532
533		if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0)
534			dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
535	}
536	bz->map_count++;
537	return (0);
538}
539
540/*
541 * Allocate a handle for mapping from kva/uva/physical
542 * address space into bus device space.
543 */
544int
545bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
546{
547	int mapsize;
548	int error = 0;
549
550	mapsize = sizeof(**mapp) + (sizeof(struct sync_list) * dmat->nsegments);
551	*mapp = (bus_dmamap_t)malloc(mapsize, M_DEVBUF, M_NOWAIT | M_ZERO);
552	if (*mapp == NULL) {
553		CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
554		return (ENOMEM);
555	}
556	(*mapp)->sync_count = 0;
557
558	if (dmat->segments == NULL) {
559		dmat->segments = (bus_dma_segment_t *)malloc(
560		    sizeof(bus_dma_segment_t) * dmat->nsegments, M_DEVBUF,
561		    M_NOWAIT);
562		if (dmat->segments == NULL) {
563			CTR3(KTR_BUSDMA, "%s: tag %p error %d",
564			    __func__, dmat, ENOMEM);
565			free(*mapp, M_DEVBUF);
566			*mapp = NULL;
567			return (ENOMEM);
568		}
569	}
570	/*
571	 * Bouncing might be required if the driver asks for an active
572	 * exclusion region, a data alignment that is stricter than 1, and/or
573	 * an active address boundary.
574	 */
575	error = allocate_bz_and_pages(dmat, *mapp);
576	if (error != 0) {
577		free(*mapp, M_DEVBUF);
578		*mapp = NULL;
579		return (error);
580	}
581	return (error);
582}
583
584/*
585 * Destroy a handle for mapping from kva/uva/physical
586 * address space into bus device space.
587 */
588int
589bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
590{
591	if (STAILQ_FIRST(&map->bpages) != NULL || map->sync_count != 0) {
592		CTR3(KTR_BUSDMA, "%s: tag %p error %d",
593		    __func__, dmat, EBUSY);
594		return (EBUSY);
595	}
596	if (dmat->bounce_zone)
597		dmat->bounce_zone->map_count--;
598	free(map, M_DEVBUF);
599	dmat->map_count--;
600	CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
601	return (0);
602}
603
604
605/*
606 * Allocate a piece of memory that can be efficiently mapped into
607 * bus device space based on the constraints lited in the dma tag.
608 * A dmamap to for use with dmamap_load is also allocated.
609 */
610int
611bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
612		 bus_dmamap_t *mapp)
613{
614	busdma_bufalloc_t ba;
615	struct busdma_bufzone *bufzone;
616	vm_memattr_t memattr;
617	int mflags;
618	int mapsize;
619	int error;
620
621	if (flags & BUS_DMA_NOWAIT)
622		mflags = M_NOWAIT;
623	else
624		mflags = M_WAITOK;
625
626	/* ARM non-snooping caches need a map for the VA cache sync structure */
627
628	mapsize = sizeof(**mapp) + (sizeof(struct sync_list) * dmat->nsegments);
629	*mapp = (bus_dmamap_t)malloc(mapsize, M_DEVBUF, M_NOWAIT | M_ZERO);
630	if (*mapp == NULL) {
631		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
632		    __func__, dmat, dmat->flags, ENOMEM);
633		return (ENOMEM);
634	}
635
636	(*mapp)->sync_count = 0;
637	/* We may need bounce pages, even for allocated memory */
638	error = allocate_bz_and_pages(dmat, *mapp);
639	if (error != 0) {
640		free(*mapp, M_DEVBUF);
641		*mapp = NULL;
642		return (error);
643	}
644
645	if (dmat->segments == NULL) {
646		dmat->segments = (bus_dma_segment_t *)malloc(
647		    sizeof(bus_dma_segment_t) * dmat->nsegments, M_DEVBUF,
648		    mflags);
649		if (dmat->segments == NULL) {
650			CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
651			    __func__, dmat, dmat->flags, ENOMEM);
652			free(*mapp, M_DEVBUF);
653			*mapp = NULL;
654			return (ENOMEM);
655		}
656	}
657
658	if (flags & BUS_DMA_ZERO)
659		mflags |= M_ZERO;
660	if (flags & BUS_DMA_COHERENT) {
661		memattr = VM_MEMATTR_UNCACHEABLE;
662		ba = coherent_allocator;
663		(*mapp)->flags |= DMAMAP_COHERENT;
664	} else {
665		memattr = VM_MEMATTR_DEFAULT;
666		ba = standard_allocator;
667		(*mapp)->flags = 0;
668	}
669
670	/*
671	 * Try to find a bufzone in the allocator that holds a cache of buffers
672	 * of the right size for this request.  If the buffer is too big to be
673	 * held in the allocator cache, this returns NULL.
674	 */
675	bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
676
677	/*
678	 * Allocate the buffer from the uma(9) allocator if...
679	 *  - It's small enough to be in the allocator (bufzone not NULL).
680	 *  - The alignment constraint isn't larger than the allocation size
681	 *    (the allocator aligns buffers to their size boundaries).
682	 *  - There's no need to handle lowaddr/highaddr exclusion zones.
683	 * else allocate non-contiguous pages if...
684	 *  - The page count that could get allocated doesn't exceed nsegments.
685	 *  - The alignment constraint isn't larger than a page boundary.
686	 *  - There are no boundary-crossing constraints.
687	 * else allocate a block of contiguous pages because one or more of the
688	 * constraints is something that only the contig allocator can fulfill.
689	 */
690	if (bufzone != NULL && dmat->alignment <= bufzone->size &&
691	    !_bus_dma_can_bounce(dmat->lowaddr, dmat->highaddr)) {
692		*vaddr = uma_zalloc(bufzone->umazone, mflags);
693	} else if (dmat->nsegments >= btoc(dmat->maxsize) &&
694	    dmat->alignment <= PAGE_SIZE && dmat->boundary == 0) {
695		*vaddr = (void *)kmem_alloc_attr(kernel_arena, dmat->maxsize,
696		    mflags, 0, dmat->lowaddr, memattr);
697	} else {
698		*vaddr = (void *)kmem_alloc_contig(kernel_arena, dmat->maxsize,
699		    mflags, 0, dmat->lowaddr, dmat->alignment, dmat->boundary,
700		    memattr);
701	}
702
703
704	if (*vaddr == NULL) {
705		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
706		    __func__, dmat, dmat->flags, ENOMEM);
707		free(*mapp, M_DEVBUF);
708		*mapp = NULL;
709		return (ENOMEM);
710	} else if ((uintptr_t)*vaddr & (dmat->alignment - 1)) {
711		printf("bus_dmamem_alloc failed to align memory properly.\n");
712	}
713	dmat->map_count++;
714
715	CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
716	    __func__, dmat, dmat->flags, 0);
717	return (0);
718}
719
720/*
721 * Free a piece of memory and it's allociated dmamap, that was allocated
722 * via bus_dmamem_alloc.  Make the same choice for free/contigfree.
723 */
724void
725bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
726{
727	struct busdma_bufzone *bufzone;
728	busdma_bufalloc_t ba;
729
730	if (map->flags & DMAMAP_COHERENT)
731		ba = coherent_allocator;
732	else
733		ba = standard_allocator;
734
735	/* Be careful not to access map from here on. */
736
737	bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
738
739	if (bufzone != NULL && dmat->alignment <= bufzone->size &&
740	    !_bus_dma_can_bounce(dmat->lowaddr, dmat->highaddr))
741		uma_zfree(bufzone->umazone, vaddr);
742	else
743		kmem_free(kernel_arena, (vm_offset_t)vaddr, dmat->maxsize);
744
745	dmat->map_count--;
746	free(map, M_DEVBUF);
747	CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat, dmat->flags);
748}
749
750static void
751_bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
752    bus_size_t buflen, int flags)
753{
754	bus_addr_t curaddr;
755	bus_size_t sgsize;
756
757	if (map->pagesneeded == 0) {
758		CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
759		    " map= %p, pagesneeded= %d",
760		    dmat->lowaddr, dmat->boundary, dmat->alignment,
761		    map, map->pagesneeded);
762		/*
763		 * Count the number of bounce pages
764		 * needed in order to complete this transfer
765		 */
766		curaddr = buf;
767		while (buflen != 0) {
768			sgsize = MIN(buflen, dmat->maxsegsz);
769			if (run_filter(dmat, curaddr, sgsize,
770			    map->flags & DMAMAP_COHERENT) != 0) {
771				sgsize = MIN(sgsize, PAGE_SIZE);
772				map->pagesneeded++;
773			}
774			curaddr += sgsize;
775			buflen -= sgsize;
776		}
777		CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
778	}
779}
780
781static void
782_bus_dmamap_count_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
783    void *buf, bus_size_t buflen, int flags)
784{
785	vm_offset_t vaddr;
786	vm_offset_t vendaddr;
787	bus_addr_t paddr;
788
789	if (map->pagesneeded == 0) {
790		CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
791		    " map= %p, pagesneeded= %d",
792		    dmat->lowaddr, dmat->boundary, dmat->alignment,
793		    map, map->pagesneeded);
794		/*
795		 * Count the number of bounce pages
796		 * needed in order to complete this transfer
797		 */
798		vaddr = (vm_offset_t)buf;
799		vendaddr = (vm_offset_t)buf + buflen;
800
801		while (vaddr < vendaddr) {
802			if (__predict_true(map->pmap == kernel_pmap))
803				paddr = pmap_kextract(vaddr);
804			else
805				paddr = pmap_extract(map->pmap, vaddr);
806			if (run_filter(dmat, paddr,
807			    min(vendaddr - vaddr,
808			    (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK))),
809			    map->flags & DMAMAP_COHERENT) != 0) {
810				map->pagesneeded++;
811			}
812			vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
813
814		}
815		CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
816	}
817}
818
819static int
820_bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int flags)
821{
822
823	/* Reserve Necessary Bounce Pages */
824	mtx_lock(&bounce_lock);
825	if (flags & BUS_DMA_NOWAIT) {
826		if (reserve_bounce_pages(dmat, map, 0) != 0) {
827			map->pagesneeded = 0;
828			mtx_unlock(&bounce_lock);
829			return (ENOMEM);
830		}
831	} else {
832		if (reserve_bounce_pages(dmat, map, 1) != 0) {
833			/* Queue us for resources */
834			STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
835			mtx_unlock(&bounce_lock);
836			return (EINPROGRESS);
837		}
838	}
839	mtx_unlock(&bounce_lock);
840
841	return (0);
842}
843
844/*
845 * Add a single contiguous physical range to the segment list.
846 */
847static int
848_bus_dmamap_addseg(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t curaddr,
849		   bus_size_t sgsize, bus_dma_segment_t *segs, int *segp)
850{
851	bus_addr_t baddr, bmask;
852	int seg;
853
854	/*
855	 * Make sure we don't cross any boundaries.
856	 */
857	bmask = ~(dmat->boundary - 1);
858	if (dmat->boundary > 0) {
859		baddr = (curaddr + dmat->boundary) & bmask;
860		if (sgsize > (baddr - curaddr))
861			sgsize = (baddr - curaddr);
862	}
863
864	if (dmat->ranges) {
865		struct arm32_dma_range *dr;
866
867		dr = _bus_dma_inrange(dmat->ranges, dmat->_nranges,
868		    curaddr);
869		if (dr == NULL) {
870			_bus_dmamap_unload(dmat, map);
871			return (0);
872		}
873		/*
874		 * In a valid DMA range.  Translate the physical
875		 * memory address to an address in the DMA window.
876		 */
877		curaddr = (curaddr - dr->dr_sysbase) + dr->dr_busbase;
878	}
879
880	/*
881	 * Insert chunk into a segment, coalescing with
882	 * previous segment if possible.
883	 */
884	seg = *segp;
885	if (seg == -1) {
886		seg = 0;
887		segs[seg].ds_addr = curaddr;
888		segs[seg].ds_len = sgsize;
889	} else {
890		if (curaddr == segs[seg].ds_addr + segs[seg].ds_len &&
891		    (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
892		    (dmat->boundary == 0 ||
893		     (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
894			segs[seg].ds_len += sgsize;
895		else {
896			if (++seg >= dmat->nsegments)
897				return (0);
898			segs[seg].ds_addr = curaddr;
899			segs[seg].ds_len = sgsize;
900		}
901	}
902	*segp = seg;
903	return (sgsize);
904}
905
906/*
907 * Utility function to load a physical buffer.  segp contains
908 * the starting segment on entrace, and the ending segment on exit.
909 */
910int
911_bus_dmamap_load_phys(bus_dma_tag_t dmat,
912		      bus_dmamap_t map,
913		      vm_paddr_t buf, bus_size_t buflen,
914		      int flags,
915		      bus_dma_segment_t *segs,
916		      int *segp)
917{
918	bus_addr_t curaddr;
919	bus_size_t sgsize;
920	int error;
921
922	if (segs == NULL)
923		segs = dmat->segments;
924
925	if (((map->flags & DMAMAP_COHERENT) == 0) ||
926	    (dmat->flags & BUS_DMA_COULD_BOUNCE) != 0) {
927		_bus_dmamap_count_phys(dmat, map, buf, buflen, flags);
928		if (map->pagesneeded != 0) {
929			error = _bus_dmamap_reserve_pages(dmat, map, flags);
930			if (error)
931				return (error);
932		}
933	}
934
935	while (buflen > 0) {
936		curaddr = buf;
937		sgsize = MIN(buflen, dmat->maxsegsz);
938		if ((((map->flags & DMAMAP_COHERENT) == 0) ||
939		    ((dmat->flags & BUS_DMA_COULD_BOUNCE) != 0)) &&
940		    map->pagesneeded != 0 && run_filter(dmat, curaddr,
941		    sgsize, map->flags & DMAMAP_COHERENT)) {
942			sgsize = MIN(sgsize, PAGE_SIZE);
943			curaddr = add_bounce_page(dmat, map, 0, curaddr,
944						  sgsize);
945		}
946		sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
947		    segp);
948		if (sgsize == 0)
949			break;
950		buf += sgsize;
951		buflen -= sgsize;
952	}
953
954	/*
955	 * Did we fit?
956	 */
957	if (buflen != 0) {
958		_bus_dmamap_unload(dmat, map);
959		return (EFBIG); /* XXX better return value here? */
960	}
961	return (0);
962}
963
964/*
965 * Utility function to load a linear buffer.  segp contains
966 * the starting segment on entrace, and the ending segment on exit.
967 */
968int
969_bus_dmamap_load_buffer(bus_dma_tag_t dmat,
970			bus_dmamap_t map,
971			void *buf, bus_size_t buflen,
972			pmap_t pmap,
973			int flags,
974			bus_dma_segment_t *segs,
975			int *segp)
976{
977	bus_size_t sgsize;
978	bus_addr_t curaddr;
979	vm_offset_t vaddr;
980	struct sync_list *sl;
981	int error;
982
983	if (segs == NULL)
984		segs = dmat->segments;
985
986	map->pmap = pmap;
987
988	if (!(map->flags & DMAMAP_COHERENT) ||
989	    (dmat->flags & BUS_DMA_COULD_BOUNCE) != 0) {
990		_bus_dmamap_count_pages(dmat, map, buf, buflen, flags);
991		if (map->pagesneeded != 0) {
992			error = _bus_dmamap_reserve_pages(dmat, map, flags);
993			if (error)
994				return (error);
995		}
996	}
997
998	sl = NULL;
999	vaddr = (vm_offset_t)buf;
1000
1001	while (buflen > 0) {
1002		/*
1003		 * Get the physical address for this segment.
1004		 */
1005		if (__predict_true(map->pmap == kernel_pmap))
1006			curaddr = pmap_kextract(vaddr);
1007		else
1008			curaddr = pmap_extract(map->pmap, vaddr);
1009
1010		/*
1011		 * Compute the segment size, and adjust counts.
1012		 */
1013		sgsize = PAGE_SIZE - ((u_long)curaddr & PAGE_MASK);
1014		if (sgsize > dmat->maxsegsz)
1015			sgsize = dmat->maxsegsz;
1016		if (buflen < sgsize)
1017			sgsize = buflen;
1018
1019		if ((((map->flags & DMAMAP_COHERENT) == 0) ||
1020		    ((dmat->flags & BUS_DMA_COULD_BOUNCE) != 0)) &&
1021		    map->pagesneeded != 0 && run_filter(dmat, curaddr,
1022		    sgsize, map->flags & DMAMAP_COHERENT)) {
1023			curaddr = add_bounce_page(dmat, map, vaddr, curaddr,
1024						  sgsize);
1025		} else {
1026			sl = &map->slist[map->sync_count - 1];
1027			if (map->sync_count == 0 ||
1028#ifdef ARM_L2_PIPT
1029			    curaddr != sl->busaddr + sl->datacount ||
1030#endif
1031			    vaddr != sl->vaddr + sl->datacount) {
1032				if (++map->sync_count > dmat->nsegments)
1033					goto cleanup;
1034				sl++;
1035				sl->vaddr = vaddr;
1036				sl->datacount = sgsize;
1037				sl->busaddr = curaddr;
1038			} else
1039				sl->datacount += sgsize;
1040		}
1041		sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1042					    segp);
1043		if (sgsize == 0)
1044			break;
1045		vaddr += sgsize;
1046		buflen -= sgsize;
1047	}
1048
1049cleanup:
1050	/*
1051	 * Did we fit?
1052	 */
1053	if (buflen != 0) {
1054		_bus_dmamap_unload(dmat, map);
1055		return (EFBIG); /* XXX better return value here? */
1056	}
1057	return (0);
1058}
1059
1060
1061void
1062__bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map,
1063		    struct memdesc *mem, bus_dmamap_callback_t *callback,
1064		    void *callback_arg)
1065{
1066
1067	map->mem = *mem;
1068	map->dmat = dmat;
1069	map->callback = callback;
1070	map->callback_arg = callback_arg;
1071}
1072
1073bus_dma_segment_t *
1074_bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map,
1075		     bus_dma_segment_t *segs, int nsegs, int error)
1076{
1077
1078	if (segs == NULL)
1079		segs = dmat->segments;
1080	return (segs);
1081}
1082
1083/*
1084 * Release the mapping held by map.
1085 */
1086void
1087_bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1088{
1089	struct bounce_page *bpage;
1090	struct bounce_zone *bz;
1091
1092	if ((bz = dmat->bounce_zone) != NULL) {
1093		while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1094			STAILQ_REMOVE_HEAD(&map->bpages, links);
1095			free_bounce_page(dmat, bpage);
1096		}
1097
1098		bz = dmat->bounce_zone;
1099		bz->free_bpages += map->pagesreserved;
1100		bz->reserved_bpages -= map->pagesreserved;
1101		map->pagesreserved = 0;
1102		map->pagesneeded = 0;
1103	}
1104	map->sync_count = 0;
1105}
1106
1107#ifdef notyetbounceuser
1108	/* If busdma uses user pages, then the interrupt handler could
1109	 * be use the kernel vm mapping. Both bounce pages and sync list
1110	 * do not cross page boundaries.
1111	 * Below is a rough sequence that a person would do to fix the
1112	 * user page reference in the kernel vmspace. This would be
1113	 * done in the dma post routine.
1114	 */
1115void
1116_bus_dmamap_fix_user(vm_offset_t buf, bus_size_t len,
1117			pmap_t pmap, int op)
1118{
1119	bus_size_t sgsize;
1120	bus_addr_t curaddr;
1121	vm_offset_t va;
1122
1123		/* each synclist entry is contained within a single page.
1124		 *
1125		 * this would be needed if BUS_DMASYNC_POSTxxxx was implemented
1126		*/
1127	curaddr = pmap_extract(pmap, buf);
1128	va = pmap_dma_map(curaddr);
1129	switch (op) {
1130	case SYNC_USER_INV:
1131		cpu_dcache_wb_range(va, sgsize);
1132		break;
1133
1134	case SYNC_USER_COPYTO:
1135		bcopy((void *)va, (void *)bounce, sgsize);
1136		break;
1137
1138	case SYNC_USER_COPYFROM:
1139		bcopy((void *) bounce, (void *)va, sgsize);
1140		break;
1141
1142	default:
1143		break;
1144	}
1145
1146	pmap_dma_unmap(va);
1147}
1148#endif
1149
1150#ifdef ARM_L2_PIPT
1151#define l2cache_wb_range(va, pa, size) cpu_l2cache_wb_range(pa, size)
1152#define l2cache_wbinv_range(va, pa, size) cpu_l2cache_wbinv_range(pa, size)
1153#define l2cache_inv_range(va, pa, size) cpu_l2cache_inv_range(pa, size)
1154#else
1155#define l2cache_wb_range(va, pa, size) cpu_l2cache_wb_range(va, size)
1156#define l2cache_wbinv_range(va, pa, size) cpu_l2cache_wbinv_range(va, size)
1157#define l2cache_inv_range(va, pa, size) cpu_l2cache_inv_range(va, size)
1158#endif
1159
1160void
1161_bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1162{
1163	struct bounce_page *bpage;
1164	struct sync_list *sl, *end;
1165	/*
1166	 * If the buffer was from user space, it is possible that this is not
1167	 * the same vm map, especially on a POST operation.  It's not clear that
1168	 * dma on userland buffers can work at all right now, certainly not if a
1169	 * partial cacheline flush has to be handled.  To be safe, until we're
1170	 * able to test direct userland dma, panic on a map mismatch.
1171	 */
1172	if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1173		if (!pmap_dmap_iscurrent(map->pmap))
1174			panic("_bus_dmamap_sync: wrong user map for bounce sync.");
1175		/* Handle data bouncing. */
1176		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1177		    "performing bounce", __func__, dmat, dmat->flags, op);
1178
1179		if (op & BUS_DMASYNC_PREWRITE) {
1180			while (bpage != NULL) {
1181				if (bpage->datavaddr != 0)
1182					bcopy((void *)bpage->datavaddr,
1183					      (void *)bpage->vaddr,
1184					      bpage->datacount);
1185				else
1186					physcopyout(bpage->dataaddr,
1187					      (void *)bpage->vaddr,
1188					      bpage->datacount);
1189				cpu_dcache_wb_range((vm_offset_t)bpage->vaddr,
1190					bpage->datacount);
1191				l2cache_wb_range((vm_offset_t)bpage->vaddr,
1192				    (vm_offset_t)bpage->busaddr,
1193				    bpage->datacount);
1194				bpage = STAILQ_NEXT(bpage, links);
1195			}
1196			dmat->bounce_zone->total_bounced++;
1197		}
1198
1199		if (op & BUS_DMASYNC_POSTREAD) {
1200			while (bpage != NULL) {
1201				vm_offset_t startv;
1202				vm_paddr_t startp;
1203				int len;
1204
1205				startv = bpage->vaddr &~ arm_dcache_align_mask;
1206				startp = bpage->busaddr &~ arm_dcache_align_mask;
1207				len = bpage->datacount;
1208
1209				if (startv != bpage->vaddr)
1210					len += bpage->vaddr & arm_dcache_align_mask;
1211				if (len & arm_dcache_align_mask)
1212					len = (len -
1213					    (len & arm_dcache_align_mask)) +
1214					    arm_dcache_align;
1215				cpu_dcache_inv_range(startv, len);
1216				l2cache_inv_range(startv, startp, len);
1217				if (bpage->datavaddr != 0)
1218					bcopy((void *)bpage->vaddr,
1219					      (void *)bpage->datavaddr,
1220					      bpage->datacount);
1221				else
1222					physcopyin((void *)bpage->vaddr,
1223					      bpage->dataaddr,
1224					      bpage->datacount);
1225				bpage = STAILQ_NEXT(bpage, links);
1226			}
1227			dmat->bounce_zone->total_bounced++;
1228		}
1229	}
1230	if (map->flags & DMAMAP_COHERENT)
1231		return;
1232
1233	if (map->sync_count != 0) {
1234		if (!pmap_dmap_iscurrent(map->pmap))
1235			panic("_bus_dmamap_sync: wrong user map for sync.");
1236		/* ARM caches are not self-snooping for dma */
1237
1238		sl = &map->slist[0];
1239		end = &map->slist[map->sync_count];
1240		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1241		    "performing sync", __func__, dmat, dmat->flags, op);
1242
1243		switch (op) {
1244		case BUS_DMASYNC_PREWRITE:
1245			while (sl != end) {
1246			    cpu_dcache_wb_range(sl->vaddr, sl->datacount);
1247			    l2cache_wb_range(sl->vaddr, sl->busaddr,
1248				sl->datacount);
1249			    sl++;
1250			}
1251			break;
1252
1253		case BUS_DMASYNC_PREREAD:
1254			while (sl != end) {
1255				cpu_dcache_inv_range(sl->vaddr, sl->datacount);
1256				l2cache_inv_range(sl->vaddr, sl->busaddr,
1257				    sl->datacount);
1258				sl++;
1259			}
1260			break;
1261
1262		case BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD:
1263			while (sl != end) {
1264				cpu_dcache_wbinv_range(sl->vaddr, sl->datacount);
1265				l2cache_wbinv_range(sl->vaddr,
1266				    sl->busaddr, sl->datacount);
1267				sl++;
1268			}
1269			break;
1270
1271		default:
1272			break;
1273		}
1274	}
1275}
1276
1277static void
1278init_bounce_pages(void *dummy __unused)
1279{
1280
1281	total_bpages = 0;
1282	STAILQ_INIT(&bounce_zone_list);
1283	STAILQ_INIT(&bounce_map_waitinglist);
1284	STAILQ_INIT(&bounce_map_callbacklist);
1285	mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
1286}
1287SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
1288
1289static struct sysctl_ctx_list *
1290busdma_sysctl_tree(struct bounce_zone *bz)
1291{
1292	return (&bz->sysctl_tree);
1293}
1294
1295static struct sysctl_oid *
1296busdma_sysctl_tree_top(struct bounce_zone *bz)
1297{
1298	return (bz->sysctl_tree_top);
1299}
1300
1301static int
1302alloc_bounce_zone(bus_dma_tag_t dmat)
1303{
1304	struct bounce_zone *bz;
1305
1306	/* Check to see if we already have a suitable zone */
1307	STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1308		if ((dmat->alignment <= bz->alignment)
1309		 && (dmat->lowaddr >= bz->lowaddr)) {
1310			dmat->bounce_zone = bz;
1311			return (0);
1312		}
1313	}
1314
1315	if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_DEVBUF,
1316	    M_NOWAIT | M_ZERO)) == NULL)
1317		return (ENOMEM);
1318
1319	STAILQ_INIT(&bz->bounce_page_list);
1320	bz->free_bpages = 0;
1321	bz->reserved_bpages = 0;
1322	bz->active_bpages = 0;
1323	bz->lowaddr = dmat->lowaddr;
1324	bz->alignment = MAX(dmat->alignment, PAGE_SIZE);
1325	bz->map_count = 0;
1326	snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1327	busdma_zonecount++;
1328	snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1329	STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1330	dmat->bounce_zone = bz;
1331
1332	sysctl_ctx_init(&bz->sysctl_tree);
1333	bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
1334	    SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1335	    CTLFLAG_RD, 0, "");
1336	if (bz->sysctl_tree_top == NULL) {
1337		sysctl_ctx_free(&bz->sysctl_tree);
1338		return (0);	/* XXX error code? */
1339	}
1340
1341	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1342	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1343	    "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1344	    "Total bounce pages");
1345	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1346	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1347	    "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1348	    "Free bounce pages");
1349	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1350	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1351	    "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1352	    "Reserved bounce pages");
1353	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1354	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1355	    "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1356	    "Active bounce pages");
1357	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1358	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1359	    "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1360	    "Total bounce requests");
1361	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1362	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1363	    "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1364	    "Total bounce requests that were deferred");
1365	SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1366	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1367	    "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1368	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1369	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1370	    "alignment", CTLFLAG_RD, &bz->alignment, 0, "");
1371
1372	return (0);
1373}
1374
1375static int
1376alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1377{
1378	struct bounce_zone *bz;
1379	int count;
1380
1381	bz = dmat->bounce_zone;
1382	count = 0;
1383	while (numpages > 0) {
1384		struct bounce_page *bpage;
1385
1386		bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_DEVBUF,
1387						     M_NOWAIT | M_ZERO);
1388
1389		if (bpage == NULL)
1390			break;
1391		bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
1392							 M_NOWAIT, 0ul,
1393							 bz->lowaddr,
1394							 PAGE_SIZE,
1395							 0);
1396		if (bpage->vaddr == 0) {
1397			free(bpage, M_DEVBUF);
1398			break;
1399		}
1400		bpage->busaddr = pmap_kextract(bpage->vaddr);
1401		mtx_lock(&bounce_lock);
1402		STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1403		total_bpages++;
1404		bz->total_bpages++;
1405		bz->free_bpages++;
1406		mtx_unlock(&bounce_lock);
1407		count++;
1408		numpages--;
1409	}
1410	return (count);
1411}
1412
1413static int
1414reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1415{
1416	struct bounce_zone *bz;
1417	int pages;
1418
1419	mtx_assert(&bounce_lock, MA_OWNED);
1420	bz = dmat->bounce_zone;
1421	pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1422	if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1423		return (map->pagesneeded - (map->pagesreserved + pages));
1424	bz->free_bpages -= pages;
1425	bz->reserved_bpages += pages;
1426	map->pagesreserved += pages;
1427	pages = map->pagesneeded - map->pagesreserved;
1428
1429	return (pages);
1430}
1431
1432static bus_addr_t
1433add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1434		bus_addr_t addr, bus_size_t size)
1435{
1436	struct bounce_zone *bz;
1437	struct bounce_page *bpage;
1438
1439	KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1440	KASSERT(map != NULL,
1441	    ("add_bounce_page: bad map %p", map));
1442
1443	bz = dmat->bounce_zone;
1444	if (map->pagesneeded == 0)
1445		panic("add_bounce_page: map doesn't need any pages");
1446	map->pagesneeded--;
1447
1448	if (map->pagesreserved == 0)
1449		panic("add_bounce_page: map doesn't need any pages");
1450	map->pagesreserved--;
1451
1452	mtx_lock(&bounce_lock);
1453	bpage = STAILQ_FIRST(&bz->bounce_page_list);
1454	if (bpage == NULL)
1455		panic("add_bounce_page: free page list is empty");
1456
1457	STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1458	bz->reserved_bpages--;
1459	bz->active_bpages++;
1460	mtx_unlock(&bounce_lock);
1461
1462	if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1463		/* Page offset needs to be preserved. */
1464		bpage->vaddr |= vaddr & PAGE_MASK;
1465		bpage->busaddr |= vaddr & PAGE_MASK;
1466	}
1467	bpage->datavaddr = vaddr;
1468	bpage->dataaddr = addr;
1469	bpage->datacount = size;
1470	STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1471	return (bpage->busaddr);
1472}
1473
1474static void
1475free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1476{
1477	struct bus_dmamap *map;
1478	struct bounce_zone *bz;
1479
1480	bz = dmat->bounce_zone;
1481	bpage->datavaddr = 0;
1482	bpage->datacount = 0;
1483	if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1484		/*
1485		 * Reset the bounce page to start at offset 0.  Other uses
1486		 * of this bounce page may need to store a full page of
1487		 * data and/or assume it starts on a page boundary.
1488		 */
1489		bpage->vaddr &= ~PAGE_MASK;
1490		bpage->busaddr &= ~PAGE_MASK;
1491	}
1492
1493	mtx_lock(&bounce_lock);
1494	STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1495	bz->free_bpages++;
1496	bz->active_bpages--;
1497	if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1498		if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1499			STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1500			STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1501					   map, links);
1502			busdma_swi_pending = 1;
1503			bz->total_deferred++;
1504			swi_sched(vm_ih, 0);
1505		}
1506	}
1507	mtx_unlock(&bounce_lock);
1508}
1509
1510void
1511busdma_swi(void)
1512{
1513	bus_dma_tag_t dmat;
1514	struct bus_dmamap *map;
1515
1516	mtx_lock(&bounce_lock);
1517	while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1518		STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1519		mtx_unlock(&bounce_lock);
1520		dmat = map->dmat;
1521		(dmat->lockfunc)(dmat->lockfuncarg, BUS_DMA_LOCK);
1522		bus_dmamap_load_mem(map->dmat, map, &map->mem, map->callback,
1523				    map->callback_arg, BUS_DMA_WAITOK);
1524		(dmat->lockfunc)(dmat->lockfuncarg, BUS_DMA_UNLOCK);
1525		mtx_lock(&bounce_lock);
1526	}
1527	mtx_unlock(&bounce_lock);
1528}
1529