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