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