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