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