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