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