busdma_machdep-v6.c revision 289893
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: head/sys/arm/arm/busdma_machdep-v6.c 289893 2015-10-24 21:27:09Z ian $");
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	vm_page_t	pages;		/* starting page of client data */
121	vm_offset_t	dataoffs;	/* page offset 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#if 0
477	if (!parent)
478		parent = arm_root_dma_tag;
479#endif
480
481	/* Basic sanity checking. */
482	KASSERT(boundary == 0 || powerof2(boundary),
483	    ("dma tag boundary %lu, must be a power of 2", boundary));
484	KASSERT(boundary == 0 || boundary >= maxsegsz,
485	    ("dma tag boundary %lu is < maxsegsz %lu\n", boundary, maxsegsz));
486	KASSERT(alignment != 0 && powerof2(alignment),
487	    ("dma tag alignment %lu, must be non-zero power of 2", alignment));
488	KASSERT(maxsegsz != 0, ("dma tag maxsegsz must not be zero"));
489
490	/* Return a NULL tag on failure */
491	*dmat = NULL;
492
493	newtag = (bus_dma_tag_t)malloc(sizeof(*newtag), M_BUSDMA,
494	    M_ZERO | M_NOWAIT);
495	if (newtag == NULL) {
496		CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
497		    __func__, newtag, 0, error);
498		return (ENOMEM);
499	}
500
501	newtag->parent = parent;
502	newtag->alignment = alignment;
503	newtag->boundary = boundary;
504	newtag->lowaddr = trunc_page((vm_paddr_t)lowaddr) + (PAGE_SIZE - 1);
505	newtag->highaddr = trunc_page((vm_paddr_t)highaddr) +
506	    (PAGE_SIZE - 1);
507	newtag->filter = filter;
508	newtag->filterarg = filterarg;
509	newtag->maxsize = maxsize;
510	newtag->nsegments = nsegments;
511	newtag->maxsegsz = maxsegsz;
512	newtag->flags = flags;
513	newtag->ref_count = 1; /* Count ourself */
514	newtag->map_count = 0;
515	newtag->ranges = bus_dma_get_range();
516	newtag->_nranges = bus_dma_get_range_nb();
517	if (lockfunc != NULL) {
518		newtag->lockfunc = lockfunc;
519		newtag->lockfuncarg = lockfuncarg;
520	} else {
521		newtag->lockfunc = dflt_lock;
522		newtag->lockfuncarg = NULL;
523	}
524
525	/* Take into account any restrictions imposed by our parent tag */
526	if (parent != NULL) {
527		newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
528		newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
529		newtag->alignment = MAX(parent->alignment, newtag->alignment);
530		newtag->flags |= parent->flags & BUS_DMA_COULD_BOUNCE;
531		if (newtag->boundary == 0)
532			newtag->boundary = parent->boundary;
533		else if (parent->boundary != 0)
534			newtag->boundary = MIN(parent->boundary,
535					       newtag->boundary);
536		if (newtag->filter == NULL) {
537			/*
538			 * Short circuit to looking at our parent directly
539			 * since we have encapsulated all of its information
540			 */
541			newtag->filter = parent->filter;
542			newtag->filterarg = parent->filterarg;
543			newtag->parent = parent->parent;
544		}
545		if (newtag->parent != NULL)
546			atomic_add_int(&parent->ref_count, 1);
547	}
548
549	if (exclusion_bounce_check(newtag->lowaddr, newtag->highaddr))
550		newtag->flags |= BUS_DMA_EXCL_BOUNCE;
551	if (alignment_bounce(newtag, 1))
552		newtag->flags |= BUS_DMA_ALIGN_BOUNCE;
553
554	/*
555	 * Any request can auto-bounce due to cacheline alignment, in addition
556	 * to any alignment or boundary specifications in the tag, so if the
557	 * ALLOCNOW flag is set, there's always work to do.
558	 */
559	if ((flags & BUS_DMA_ALLOCNOW) != 0) {
560		struct bounce_zone *bz;
561		/*
562		 * Round size up to a full page, and add one more page because
563		 * there can always be one more boundary crossing than the
564		 * number of pages in a transfer.
565		 */
566		maxsize = roundup2(maxsize, PAGE_SIZE) + PAGE_SIZE;
567
568		if ((error = alloc_bounce_zone(newtag)) != 0) {
569			free(newtag, M_BUSDMA);
570			return (error);
571		}
572		bz = newtag->bounce_zone;
573
574		if (ptoa(bz->total_bpages) < maxsize) {
575			int pages;
576
577			pages = atop(maxsize) - bz->total_bpages;
578
579			/* Add pages to our bounce pool */
580			if (alloc_bounce_pages(newtag, pages) < pages)
581				error = ENOMEM;
582		}
583		/* Performed initial allocation */
584		newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
585	} else
586		newtag->bounce_zone = NULL;
587
588	if (error != 0) {
589		free(newtag, M_BUSDMA);
590	} else {
591		atomic_add_32(&tags_total, 1);
592		*dmat = newtag;
593	}
594	CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
595	    __func__, newtag, (newtag != NULL ? newtag->flags : 0), error);
596	return (error);
597}
598
599int
600bus_dma_tag_destroy(bus_dma_tag_t dmat)
601{
602	bus_dma_tag_t dmat_copy;
603	int error;
604
605	error = 0;
606	dmat_copy = dmat;
607
608	if (dmat != NULL) {
609
610		if (dmat->map_count != 0) {
611			error = EBUSY;
612			goto out;
613		}
614
615		while (dmat != NULL) {
616			bus_dma_tag_t parent;
617
618			parent = dmat->parent;
619			atomic_subtract_int(&dmat->ref_count, 1);
620			if (dmat->ref_count == 0) {
621				atomic_subtract_32(&tags_total, 1);
622				free(dmat, M_BUSDMA);
623				/*
624				 * Last reference count, so
625				 * release our reference
626				 * count on our parent.
627				 */
628				dmat = parent;
629			} else
630				dmat = NULL;
631		}
632	}
633out:
634	CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
635	return (error);
636}
637
638static int
639allocate_bz_and_pages(bus_dma_tag_t dmat, bus_dmamap_t mapp)
640{
641	struct bounce_zone *bz;
642	int maxpages;
643	int error;
644
645	if (dmat->bounce_zone == NULL)
646		if ((error = alloc_bounce_zone(dmat)) != 0)
647			return (error);
648	bz = dmat->bounce_zone;
649	/* Initialize the new map */
650	STAILQ_INIT(&(mapp->bpages));
651
652	/*
653	 * Attempt to add pages to our pool on a per-instance basis up to a sane
654	 * limit.  Even if the tag isn't flagged as COULD_BOUNCE due to
655	 * alignment and boundary constraints, it could still auto-bounce due to
656	 * cacheline alignment, which requires at most two bounce pages.
657	 */
658	if (dmat->flags & BUS_DMA_COULD_BOUNCE)
659		maxpages = MAX_BPAGES;
660	else
661		maxpages = 2 * bz->map_count;
662	if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0 ||
663	    (bz->map_count > 0 && bz->total_bpages < maxpages)) {
664		int pages;
665
666		pages = atop(roundup2(dmat->maxsize, PAGE_SIZE)) + 1;
667		pages = MIN(maxpages - bz->total_bpages, pages);
668		pages = MAX(pages, 2);
669		if (alloc_bounce_pages(dmat, pages) < pages)
670			return (ENOMEM);
671
672		if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0)
673			dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
674	}
675	bz->map_count++;
676	return (0);
677}
678
679static bus_dmamap_t
680allocate_map(bus_dma_tag_t dmat, int mflags)
681{
682	int mapsize, segsize;
683	bus_dmamap_t map;
684
685	/*
686	 * Allocate the map.  The map structure ends with an embedded
687	 * variable-sized array of sync_list structures.  Following that
688	 * we allocate enough extra space to hold the array of bus_dma_segments.
689	 */
690	KASSERT(dmat->nsegments <= MAX_DMA_SEGMENTS,
691	   ("cannot allocate %u dma segments (max is %u)",
692	    dmat->nsegments, MAX_DMA_SEGMENTS));
693	segsize = sizeof(struct bus_dma_segment) * dmat->nsegments;
694	mapsize = sizeof(*map) + sizeof(struct sync_list) * dmat->nsegments;
695	map = malloc(mapsize + segsize, M_BUSDMA, mflags | M_ZERO);
696	if (map == NULL) {
697		CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
698		return (NULL);
699	}
700	map->segments = (bus_dma_segment_t *)((uintptr_t)map + mapsize);
701	return (map);
702}
703
704/*
705 * Allocate a handle for mapping from kva/uva/physical
706 * address space into bus device space.
707 */
708int
709bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
710{
711	bus_dmamap_t map;
712	int error = 0;
713
714	*mapp = map = allocate_map(dmat, M_NOWAIT);
715	if (map == NULL) {
716		CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
717		return (ENOMEM);
718	}
719
720	/*
721	 * Bouncing might be required if the driver asks for an exclusion
722	 * region, a data alignment that is stricter than 1, or DMA that begins
723	 * or ends with a partial cacheline.  Whether bouncing will actually
724	 * happen can't be known until mapping time, but we need to pre-allocate
725	 * resources now because we might not be allowed to at mapping time.
726	 */
727	error = allocate_bz_and_pages(dmat, map);
728	if (error != 0) {
729		free(map, M_BUSDMA);
730		*mapp = NULL;
731		return (error);
732	}
733	if (map->flags & DMAMAP_COHERENT)
734		atomic_add_32(&maps_coherent, 1);
735	atomic_add_32(&maps_total, 1);
736	dmat->map_count++;
737
738	return (0);
739}
740
741/*
742 * Destroy a handle for mapping from kva/uva/physical
743 * address space into bus device space.
744 */
745int
746bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
747{
748
749	if (STAILQ_FIRST(&map->bpages) != NULL || map->sync_count != 0) {
750		CTR3(KTR_BUSDMA, "%s: tag %p error %d",
751		    __func__, dmat, EBUSY);
752		return (EBUSY);
753	}
754	if (dmat->bounce_zone)
755		dmat->bounce_zone->map_count--;
756	if (map->flags & DMAMAP_COHERENT)
757		atomic_subtract_32(&maps_coherent, 1);
758	atomic_subtract_32(&maps_total, 1);
759	free(map, M_BUSDMA);
760	dmat->map_count--;
761	CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
762	return (0);
763}
764
765/*
766 * Allocate a piece of memory that can be efficiently mapped into bus device
767 * space based on the constraints listed in the dma tag.  Returns a pointer to
768 * the allocated memory, and a pointer to an associated bus_dmamap.
769 */
770int
771bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
772    bus_dmamap_t *mapp)
773{
774	busdma_bufalloc_t ba;
775	struct busdma_bufzone *bufzone;
776	bus_dmamap_t map;
777	vm_memattr_t memattr;
778	int mflags;
779
780	if (flags & BUS_DMA_NOWAIT)
781		mflags = M_NOWAIT;
782	else
783		mflags = M_WAITOK;
784	if (flags & BUS_DMA_ZERO)
785		mflags |= M_ZERO;
786
787	*mapp = map = allocate_map(dmat, mflags);
788	if (map == NULL) {
789		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
790		    __func__, dmat, dmat->flags, ENOMEM);
791		return (ENOMEM);
792	}
793	map->flags = DMAMAP_DMAMEM_ALLOC;
794
795	/* Choose a busdma buffer allocator based on memory type flags. */
796	if (flags & BUS_DMA_COHERENT) {
797		memattr = VM_MEMATTR_UNCACHEABLE;
798		ba = coherent_allocator;
799		map->flags |= DMAMAP_COHERENT;
800	} else {
801		memattr = VM_MEMATTR_DEFAULT;
802		ba = standard_allocator;
803	}
804
805	/*
806	 * Try to find a bufzone in the allocator that holds a cache of buffers
807	 * of the right size for this request.  If the buffer is too big to be
808	 * held in the allocator cache, this returns NULL.
809	 */
810	bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
811
812	/*
813	 * Allocate the buffer from the uma(9) allocator if...
814	 *  - It's small enough to be in the allocator (bufzone not NULL).
815	 *  - The alignment constraint isn't larger than the allocation size
816	 *    (the allocator aligns buffers to their size boundaries).
817	 *  - There's no need to handle lowaddr/highaddr exclusion zones.
818	 * else allocate non-contiguous pages if...
819	 *  - The page count that could get allocated doesn't exceed nsegments.
820	 *  - The alignment constraint isn't larger than a page boundary.
821	 *  - There are no boundary-crossing constraints.
822	 * else allocate a block of contiguous pages because one or more of the
823	 * constraints is something that only the contig allocator can fulfill.
824	 */
825	if (bufzone != NULL && dmat->alignment <= bufzone->size &&
826	    !exclusion_bounce(dmat)) {
827		*vaddr = uma_zalloc(bufzone->umazone, mflags);
828	} else if (dmat->nsegments >= btoc(dmat->maxsize) &&
829	    dmat->alignment <= PAGE_SIZE && dmat->boundary == 0) {
830		*vaddr = (void *)kmem_alloc_attr(kernel_arena, dmat->maxsize,
831		    mflags, 0, dmat->lowaddr, memattr);
832	} else {
833		*vaddr = (void *)kmem_alloc_contig(kernel_arena, dmat->maxsize,
834		    mflags, 0, dmat->lowaddr, dmat->alignment, dmat->boundary,
835		    memattr);
836	}
837	if (*vaddr == NULL) {
838		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
839		    __func__, dmat, dmat->flags, ENOMEM);
840		free(map, M_BUSDMA);
841		*mapp = NULL;
842		return (ENOMEM);
843	}
844	if (map->flags & DMAMAP_COHERENT)
845		atomic_add_32(&maps_coherent, 1);
846	atomic_add_32(&maps_dmamem, 1);
847	atomic_add_32(&maps_total, 1);
848	dmat->map_count++;
849
850	CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
851	    __func__, dmat, dmat->flags, 0);
852	return (0);
853}
854
855/*
856 * Free a piece of memory that was allocated via bus_dmamem_alloc, along with
857 * its associated map.
858 */
859void
860bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
861{
862	struct busdma_bufzone *bufzone;
863	busdma_bufalloc_t ba;
864
865	if (map->flags & DMAMAP_COHERENT)
866		ba = coherent_allocator;
867	else
868		ba = standard_allocator;
869
870	bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
871
872	if (bufzone != NULL && dmat->alignment <= bufzone->size &&
873	    !exclusion_bounce(dmat))
874		uma_zfree(bufzone->umazone, vaddr);
875	else
876		kmem_free(kernel_arena, (vm_offset_t)vaddr, dmat->maxsize);
877
878	dmat->map_count--;
879	if (map->flags & DMAMAP_COHERENT)
880		atomic_subtract_32(&maps_coherent, 1);
881	atomic_subtract_32(&maps_total, 1);
882	atomic_subtract_32(&maps_dmamem, 1);
883	free(map, M_BUSDMA);
884	CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat, dmat->flags);
885}
886
887static void
888_bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
889    bus_size_t buflen, int flags)
890{
891	bus_addr_t curaddr;
892	bus_size_t sgsize;
893
894	if (map->pagesneeded == 0) {
895		CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
896		    " map= %p, pagesneeded= %d",
897		    dmat->lowaddr, dmat->boundary, dmat->alignment,
898		    map, map->pagesneeded);
899		/*
900		 * Count the number of bounce pages
901		 * needed in order to complete this transfer
902		 */
903		curaddr = buf;
904		while (buflen != 0) {
905			sgsize = MIN(buflen, dmat->maxsegsz);
906			if (must_bounce(dmat, map, curaddr, sgsize) != 0) {
907				sgsize = MIN(sgsize,
908				    PAGE_SIZE - (curaddr & PAGE_MASK));
909				map->pagesneeded++;
910			}
911			curaddr += sgsize;
912			buflen -= sgsize;
913		}
914		CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
915	}
916}
917
918static void
919_bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap, bus_dmamap_t map,
920    void *buf, bus_size_t buflen, int flags)
921{
922	vm_offset_t vaddr;
923	vm_offset_t vendaddr;
924	bus_addr_t paddr;
925
926	if (map->pagesneeded == 0) {
927		CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
928		    " map= %p, pagesneeded= %d",
929		    dmat->lowaddr, dmat->boundary, dmat->alignment,
930		    map, map->pagesneeded);
931		/*
932		 * Count the number of bounce pages
933		 * needed in order to complete this transfer
934		 */
935		vaddr = (vm_offset_t)buf;
936		vendaddr = (vm_offset_t)buf + buflen;
937
938		while (vaddr < vendaddr) {
939			if (__predict_true(pmap == kernel_pmap))
940				paddr = pmap_kextract(vaddr);
941			else
942				paddr = pmap_extract(pmap, vaddr);
943			if (must_bounce(dmat, map, paddr,
944			    min(vendaddr - vaddr, (PAGE_SIZE - ((vm_offset_t)vaddr &
945			    PAGE_MASK)))) != 0) {
946				map->pagesneeded++;
947			}
948			vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
949
950		}
951		CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
952	}
953}
954
955static int
956_bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int flags)
957{
958
959	/* Reserve Necessary Bounce Pages */
960	mtx_lock(&bounce_lock);
961	if (flags & BUS_DMA_NOWAIT) {
962		if (reserve_bounce_pages(dmat, map, 0) != 0) {
963			map->pagesneeded = 0;
964			mtx_unlock(&bounce_lock);
965			return (ENOMEM);
966		}
967	} else {
968		if (reserve_bounce_pages(dmat, map, 1) != 0) {
969			/* Queue us for resources */
970			STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
971			mtx_unlock(&bounce_lock);
972			return (EINPROGRESS);
973		}
974	}
975	mtx_unlock(&bounce_lock);
976
977	return (0);
978}
979
980/*
981 * Add a single contiguous physical range to the segment list.
982 */
983static int
984_bus_dmamap_addseg(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t curaddr,
985    bus_size_t sgsize, bus_dma_segment_t *segs, int *segp)
986{
987	bus_addr_t baddr, bmask;
988	int seg;
989
990	/*
991	 * Make sure we don't cross any boundaries.
992	 */
993	bmask = ~(dmat->boundary - 1);
994	if (dmat->boundary > 0) {
995		baddr = (curaddr + dmat->boundary) & bmask;
996		if (sgsize > (baddr - curaddr))
997			sgsize = (baddr - curaddr);
998	}
999
1000	if (dmat->ranges) {
1001		struct arm32_dma_range *dr;
1002
1003		dr = _bus_dma_inrange(dmat->ranges, dmat->_nranges,
1004		    curaddr);
1005		if (dr == NULL) {
1006			_bus_dmamap_unload(dmat, map);
1007			return (0);
1008		}
1009		/*
1010		 * In a valid DMA range.  Translate the physical
1011		 * memory address to an address in the DMA window.
1012		 */
1013		curaddr = (curaddr - dr->dr_sysbase) + dr->dr_busbase;
1014	}
1015
1016	/*
1017	 * Insert chunk into a segment, coalescing with
1018	 * previous segment if possible.
1019	 */
1020	seg = *segp;
1021	if (seg == -1) {
1022		seg = 0;
1023		segs[seg].ds_addr = curaddr;
1024		segs[seg].ds_len = sgsize;
1025	} else {
1026		if (curaddr == segs[seg].ds_addr + segs[seg].ds_len &&
1027		    (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
1028		    (dmat->boundary == 0 ||
1029		    (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
1030			segs[seg].ds_len += sgsize;
1031		else {
1032			if (++seg >= dmat->nsegments)
1033				return (0);
1034			segs[seg].ds_addr = curaddr;
1035			segs[seg].ds_len = sgsize;
1036		}
1037	}
1038	*segp = seg;
1039	return (sgsize);
1040}
1041
1042/*
1043 * Utility function to load a physical buffer.  segp contains
1044 * the starting segment on entrace, and the ending segment on exit.
1045 */
1046int
1047_bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
1048    bus_size_t buflen, int flags, bus_dma_segment_t *segs, int *segp)
1049{
1050	bus_addr_t curaddr;
1051	bus_addr_t sl_end = 0;
1052	bus_size_t sgsize;
1053	struct sync_list *sl;
1054	int error;
1055
1056	if (segs == NULL)
1057		segs = map->segments;
1058
1059	counter_u64_add(maploads_total, 1);
1060	counter_u64_add(maploads_physmem, 1);
1061
1062	if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1063		_bus_dmamap_count_phys(dmat, map, buf, buflen, flags);
1064		if (map->pagesneeded != 0) {
1065			counter_u64_add(maploads_bounced, 1);
1066			error = _bus_dmamap_reserve_pages(dmat, map, flags);
1067			if (error)
1068				return (error);
1069		}
1070	}
1071
1072	sl = map->slist + map->sync_count - 1;
1073
1074	while (buflen > 0) {
1075		curaddr = buf;
1076		sgsize = MIN(buflen, dmat->maxsegsz);
1077		if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1078		    sgsize)) {
1079			sgsize = MIN(sgsize, PAGE_SIZE - (curaddr & PAGE_MASK));
1080			curaddr = add_bounce_page(dmat, map, 0, curaddr,
1081			    sgsize);
1082		} else {
1083			if (map->sync_count > 0)
1084				sl_end = VM_PAGE_TO_PHYS(sl->pages) +
1085				    sl->dataoffs + sl->datacount;
1086
1087			if (map->sync_count == 0 || curaddr != sl_end) {
1088				if (++map->sync_count > dmat->nsegments)
1089					break;
1090				sl++;
1091				sl->vaddr = 0;
1092				sl->datacount = sgsize;
1093				sl->pages = PHYS_TO_VM_PAGE(curaddr);
1094				sl->dataoffs = curaddr & PAGE_MASK;
1095			} else
1096				sl->datacount += sgsize;
1097		}
1098		sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1099		    segp);
1100		if (sgsize == 0)
1101			break;
1102		buf += sgsize;
1103		buflen -= sgsize;
1104	}
1105
1106	/*
1107	 * Did we fit?
1108	 */
1109	if (buflen != 0) {
1110		_bus_dmamap_unload(dmat, map);
1111		return (EFBIG); /* XXX better return value here? */
1112	}
1113	return (0);
1114}
1115
1116int
1117_bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map,
1118    struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
1119    bus_dma_segment_t *segs, int *segp)
1120{
1121
1122	return (bus_dmamap_load_ma_triv(dmat, map, ma, tlen, ma_offs, flags,
1123	    segs, segp));
1124}
1125
1126/*
1127 * Utility function to load a linear buffer.  segp contains
1128 * the starting segment on entrance, and the ending segment on exit.
1129 */
1130int
1131_bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
1132    bus_size_t buflen, pmap_t pmap, int flags, bus_dma_segment_t *segs,
1133    int *segp)
1134{
1135	bus_size_t sgsize;
1136	bus_addr_t curaddr;
1137	bus_addr_t sl_pend = 0;
1138	vm_offset_t kvaddr, vaddr, sl_vend = 0;
1139	struct sync_list *sl;
1140	int error;
1141
1142	counter_u64_add(maploads_total, 1);
1143	if (map->flags & DMAMAP_COHERENT)
1144		counter_u64_add(maploads_coherent, 1);
1145	if (map->flags & DMAMAP_DMAMEM_ALLOC)
1146		counter_u64_add(maploads_dmamem, 1);
1147
1148	if (segs == NULL)
1149		segs = map->segments;
1150
1151	if (flags & BUS_DMA_LOAD_MBUF) {
1152		counter_u64_add(maploads_mbuf, 1);
1153		map->flags |= DMAMAP_MBUF;
1154	}
1155
1156	if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1157		_bus_dmamap_count_pages(dmat, pmap, map, buf, buflen, flags);
1158		if (map->pagesneeded != 0) {
1159			counter_u64_add(maploads_bounced, 1);
1160			error = _bus_dmamap_reserve_pages(dmat, map, flags);
1161			if (error)
1162				return (error);
1163		}
1164	}
1165
1166	sl = map->slist + map->sync_count - 1;
1167	vaddr = (vm_offset_t)buf;
1168
1169	while (buflen > 0) {
1170		/*
1171		 * Get the physical address for this segment.
1172		 */
1173		if (__predict_true(pmap == kernel_pmap)) {
1174			curaddr = pmap_kextract(vaddr);
1175			kvaddr = vaddr;
1176		} else {
1177			curaddr = pmap_extract(pmap, vaddr);
1178			kvaddr = 0;
1179		}
1180
1181		/*
1182		 * Compute the segment size, and adjust counts.
1183		 */
1184		sgsize = PAGE_SIZE - (curaddr & PAGE_MASK);
1185		if (sgsize > dmat->maxsegsz)
1186			sgsize = dmat->maxsegsz;
1187		if (buflen < sgsize)
1188			sgsize = buflen;
1189
1190		if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1191		    sgsize)) {
1192			curaddr = add_bounce_page(dmat, map, kvaddr, curaddr,
1193			    sgsize);
1194		} else {
1195			if (map->sync_count > 0) {
1196				sl_pend = VM_PAGE_TO_PHYS(sl->pages) +
1197				    sl->dataoffs + sl->datacount;
1198				sl_vend = sl->vaddr + sl->datacount;
1199			}
1200
1201			if (map->sync_count == 0 ||
1202			    (kvaddr != 0 && kvaddr != sl_vend) ||
1203			    (curaddr != sl_pend)) {
1204
1205				if (++map->sync_count > dmat->nsegments)
1206					goto cleanup;
1207				sl++;
1208				sl->vaddr = kvaddr;
1209				sl->datacount = sgsize;
1210				sl->pages = PHYS_TO_VM_PAGE(curaddr);
1211				sl->dataoffs = curaddr & PAGE_MASK;
1212			} else
1213				sl->datacount += sgsize;
1214		}
1215		sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1216		    segp);
1217		if (sgsize == 0)
1218			break;
1219		vaddr += sgsize;
1220		buflen -= sgsize;
1221	}
1222
1223cleanup:
1224	/*
1225	 * Did we fit?
1226	 */
1227	if (buflen != 0) {
1228		_bus_dmamap_unload(dmat, map);
1229		return (EFBIG); /* XXX better return value here? */
1230	}
1231	return (0);
1232}
1233
1234void
1235__bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map, struct memdesc *mem,
1236    bus_dmamap_callback_t *callback, void *callback_arg)
1237{
1238
1239	map->mem = *mem;
1240	map->dmat = dmat;
1241	map->callback = callback;
1242	map->callback_arg = callback_arg;
1243}
1244
1245bus_dma_segment_t *
1246_bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map,
1247    bus_dma_segment_t *segs, int nsegs, int error)
1248{
1249
1250	if (segs == NULL)
1251		segs = map->segments;
1252	return (segs);
1253}
1254
1255/*
1256 * Release the mapping held by map.
1257 */
1258void
1259_bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1260{
1261	struct bounce_page *bpage;
1262	struct bounce_zone *bz;
1263
1264	if ((bz = dmat->bounce_zone) != NULL) {
1265		while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1266			STAILQ_REMOVE_HEAD(&map->bpages, links);
1267			free_bounce_page(dmat, bpage);
1268		}
1269
1270		bz = dmat->bounce_zone;
1271		bz->free_bpages += map->pagesreserved;
1272		bz->reserved_bpages -= map->pagesreserved;
1273		map->pagesreserved = 0;
1274		map->pagesneeded = 0;
1275	}
1276	map->sync_count = 0;
1277	map->flags &= ~DMAMAP_MBUF;
1278}
1279
1280static void
1281dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size)
1282{
1283	/*
1284	 * Write back any partial cachelines immediately before and
1285	 * after the DMA region.  We don't need to round the address
1286	 * down to the nearest cacheline or specify the exact size,
1287	 * as dcache_wb_poc() will do the rounding for us and works
1288	 * at cacheline granularity.
1289	 */
1290	if (va & BUSDMA_DCACHE_MASK)
1291		dcache_wb_poc(va, pa, 1);
1292	if ((va + size) & BUSDMA_DCACHE_MASK)
1293		dcache_wb_poc(va + size, pa + size, 1);
1294
1295	dcache_inv_poc_dma(va, pa, size);
1296}
1297
1298static void
1299dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op)
1300{
1301	uint32_t len, offset;
1302	vm_page_t m;
1303	vm_paddr_t pa;
1304	vm_offset_t va, tempva;
1305	bus_size_t size;
1306
1307	offset = sl->dataoffs;
1308	m = sl->pages;
1309	size = sl->datacount;
1310	pa = VM_PAGE_TO_PHYS(m) | offset;
1311
1312	for ( ; size != 0; size -= len, pa += len, offset = 0, ++m) {
1313		tempva = 0;
1314		if (sl->vaddr == 0) {
1315			len = min(PAGE_SIZE - offset, size);
1316			tempva = pmap_quick_enter_page(m);
1317			va = tempva | offset;
1318		} else {
1319			len = sl->datacount;
1320			va = sl->vaddr;
1321		}
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
1326		switch (op) {
1327		case BUS_DMASYNC_PREWRITE:
1328		case BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD:
1329			dcache_wb_poc(va, pa, len);
1330			break;
1331		case BUS_DMASYNC_PREREAD:
1332			/*
1333			 * An mbuf may start in the middle of a cacheline. There
1334			 * will be no cpu writes to the beginning of that line
1335			 * (which contains the mbuf header) while dma is in
1336			 * progress.  Handle that case by doing a writeback of
1337			 * just the first cacheline before invalidating the
1338			 * overall buffer.  Any mbuf in a chain may have this
1339			 * misalignment.  Buffers which are not mbufs bounce if
1340			 * they are not aligned to a cacheline.
1341			 */
1342			dma_preread_safe(va, pa, len);
1343			break;
1344		case BUS_DMASYNC_POSTREAD:
1345		case BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE:
1346			dcache_inv_poc(va, pa, len);
1347			break;
1348		default:
1349			panic("unsupported combination of sync operations: "
1350                              "0x%08x\n", op);
1351		}
1352
1353		if (tempva != 0)
1354			pmap_quick_remove_page(tempva);
1355	}
1356}
1357
1358void
1359_bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1360{
1361	struct bounce_page *bpage;
1362	struct sync_list *sl, *end;
1363	vm_offset_t datavaddr, tempvaddr;
1364
1365	if (op == BUS_DMASYNC_POSTWRITE)
1366		return;
1367
1368	/*
1369	 * If the buffer was from user space, it is possible that this is not
1370	 * the same vm map, especially on a POST operation.  It's not clear that
1371	 * dma on userland buffers can work at all right now.  To be safe, until
1372	 * we're able to test direct userland dma, panic on a map mismatch.
1373	 */
1374	if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1375
1376		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1377		    "performing bounce", __func__, dmat, dmat->flags, op);
1378
1379		/*
1380		 * For PREWRITE do a writeback.  Clean the caches from the
1381		 * innermost to the outermost levels.
1382		 */
1383		if (op & BUS_DMASYNC_PREWRITE) {
1384			while (bpage != NULL) {
1385				tempvaddr = 0;
1386				datavaddr = bpage->datavaddr;
1387				if (datavaddr == 0) {
1388					tempvaddr = pmap_quick_enter_page(
1389					    bpage->datapage);
1390					datavaddr = tempvaddr | bpage->dataoffs;
1391				}
1392				bcopy((void *)datavaddr, (void *)bpage->vaddr,
1393				    bpage->datacount);
1394				if (tempvaddr != 0)
1395					pmap_quick_remove_page(tempvaddr);
1396				dcache_wb_poc(bpage->vaddr, bpage->busaddr,
1397				    bpage->datacount);
1398				bpage = STAILQ_NEXT(bpage, links);
1399			}
1400			dmat->bounce_zone->total_bounced++;
1401		}
1402
1403		/*
1404		 * Do an invalidate for PREREAD unless a writeback was already
1405		 * done above due to PREWRITE also being set.  The reason for a
1406		 * PREREAD invalidate is to prevent dirty lines currently in the
1407		 * cache from being evicted during the DMA.  If a writeback was
1408		 * done due to PREWRITE also being set there will be no dirty
1409		 * lines and the POSTREAD invalidate handles the rest. The
1410		 * invalidate is done from the innermost to outermost level. If
1411		 * L2 were done first, a dirty cacheline could be automatically
1412		 * evicted from L1 before we invalidated it, re-dirtying the L2.
1413		 */
1414		if ((op & BUS_DMASYNC_PREREAD) && !(op & BUS_DMASYNC_PREWRITE)) {
1415			bpage = STAILQ_FIRST(&map->bpages);
1416			while (bpage != NULL) {
1417				dcache_inv_poc_dma(bpage->vaddr, bpage->busaddr,
1418				    bpage->datacount);
1419				bpage = STAILQ_NEXT(bpage, links);
1420			}
1421		}
1422
1423		/*
1424		 * Re-invalidate the caches on a POSTREAD, even though they were
1425		 * already invalidated at PREREAD time.  Aggressive prefetching
1426		 * due to accesses to other data near the dma buffer could have
1427		 * brought buffer data into the caches which is now stale.  The
1428		 * caches are invalidated from the outermost to innermost; the
1429		 * prefetches could be happening right now, and if L1 were
1430		 * invalidated first, stale L2 data could be prefetched into L1.
1431		 */
1432		if (op & BUS_DMASYNC_POSTREAD) {
1433			while (bpage != NULL) {
1434				dcache_inv_poc(bpage->vaddr, bpage->busaddr,
1435				    bpage->datacount);
1436				tempvaddr = 0;
1437				datavaddr = bpage->datavaddr;
1438				if (datavaddr == 0) {
1439					tempvaddr = pmap_quick_enter_page(
1440					    bpage->datapage);
1441					datavaddr = tempvaddr | bpage->dataoffs;
1442				}
1443				bcopy((void *)bpage->vaddr, (void *)datavaddr,
1444				    bpage->datacount);
1445				if (tempvaddr != 0)
1446					pmap_quick_remove_page(tempvaddr);
1447				bpage = STAILQ_NEXT(bpage, links);
1448			}
1449			dmat->bounce_zone->total_bounced++;
1450		}
1451	}
1452
1453	/*
1454	 * For COHERENT memory no cache maintenance is necessary, but ensure all
1455	 * writes have reached memory for the PREWRITE case.  No action is
1456	 * needed for a PREREAD without PREWRITE also set, because that would
1457	 * imply that the cpu had written to the COHERENT buffer and expected
1458	 * the dma device to see that change, and by definition a PREWRITE sync
1459	 * is required to make that happen.
1460	 */
1461	if (map->flags & DMAMAP_COHERENT) {
1462		if (op & BUS_DMASYNC_PREWRITE) {
1463			dsb();
1464			cpu_l2cache_drain_writebuf();
1465		}
1466		return;
1467	}
1468
1469	/*
1470	 * Cache maintenance for normal (non-COHERENT non-bounce) buffers.  All
1471	 * the comments about the sequences for flushing cache levels in the
1472	 * bounce buffer code above apply here as well.  In particular, the fact
1473	 * that the sequence is inner-to-outer for PREREAD invalidation and
1474	 * outer-to-inner for POSTREAD invalidation is not a mistake.
1475	 */
1476	if (map->sync_count != 0) {
1477		sl = &map->slist[0];
1478		end = &map->slist[map->sync_count];
1479		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1480		    "performing sync", __func__, dmat, dmat->flags, op);
1481
1482		for ( ; sl != end; ++sl)
1483			dma_dcache_sync(sl, op);
1484	}
1485}
1486
1487static void
1488init_bounce_pages(void *dummy __unused)
1489{
1490
1491	total_bpages = 0;
1492	STAILQ_INIT(&bounce_zone_list);
1493	STAILQ_INIT(&bounce_map_waitinglist);
1494	STAILQ_INIT(&bounce_map_callbacklist);
1495	mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
1496}
1497SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
1498
1499static struct sysctl_ctx_list *
1500busdma_sysctl_tree(struct bounce_zone *bz)
1501{
1502
1503	return (&bz->sysctl_tree);
1504}
1505
1506static struct sysctl_oid *
1507busdma_sysctl_tree_top(struct bounce_zone *bz)
1508{
1509
1510	return (bz->sysctl_tree_top);
1511}
1512
1513static int
1514alloc_bounce_zone(bus_dma_tag_t dmat)
1515{
1516	struct bounce_zone *bz;
1517
1518	/* Check to see if we already have a suitable zone */
1519	STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1520		if ((dmat->alignment <= bz->alignment) &&
1521		    (dmat->lowaddr >= bz->lowaddr)) {
1522			dmat->bounce_zone = bz;
1523			return (0);
1524		}
1525	}
1526
1527	if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_BUSDMA,
1528	    M_NOWAIT | M_ZERO)) == NULL)
1529		return (ENOMEM);
1530
1531	STAILQ_INIT(&bz->bounce_page_list);
1532	bz->free_bpages = 0;
1533	bz->reserved_bpages = 0;
1534	bz->active_bpages = 0;
1535	bz->lowaddr = dmat->lowaddr;
1536	bz->alignment = MAX(dmat->alignment, PAGE_SIZE);
1537	bz->map_count = 0;
1538	snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1539	busdma_zonecount++;
1540	snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1541	STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1542	dmat->bounce_zone = bz;
1543
1544	sysctl_ctx_init(&bz->sysctl_tree);
1545	bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
1546	    SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1547	    CTLFLAG_RD, 0, "");
1548	if (bz->sysctl_tree_top == NULL) {
1549		sysctl_ctx_free(&bz->sysctl_tree);
1550		return (0);	/* XXX error code? */
1551	}
1552
1553	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1554	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1555	    "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1556	    "Total bounce pages");
1557	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1558	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1559	    "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1560	    "Free bounce pages");
1561	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1562	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1563	    "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1564	    "Reserved bounce pages");
1565	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1566	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1567	    "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1568	    "Active bounce pages");
1569	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1570	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1571	    "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1572	    "Total bounce requests (pages bounced)");
1573	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1574	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1575	    "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1576	    "Total bounce requests that were deferred");
1577	SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1578	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1579	    "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1580	SYSCTL_ADD_ULONG(busdma_sysctl_tree(bz),
1581	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1582	    "alignment", CTLFLAG_RD, &bz->alignment, "");
1583
1584	return (0);
1585}
1586
1587static int
1588alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1589{
1590	struct bounce_zone *bz;
1591	int count;
1592
1593	bz = dmat->bounce_zone;
1594	count = 0;
1595	while (numpages > 0) {
1596		struct bounce_page *bpage;
1597
1598		bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_BUSDMA,
1599		    M_NOWAIT | M_ZERO);
1600
1601		if (bpage == NULL)
1602			break;
1603		bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_BOUNCE,
1604		    M_NOWAIT, 0ul, bz->lowaddr, PAGE_SIZE, 0);
1605		if (bpage->vaddr == 0) {
1606			free(bpage, M_BUSDMA);
1607			break;
1608		}
1609		bpage->busaddr = pmap_kextract(bpage->vaddr);
1610		mtx_lock(&bounce_lock);
1611		STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1612		total_bpages++;
1613		bz->total_bpages++;
1614		bz->free_bpages++;
1615		mtx_unlock(&bounce_lock);
1616		count++;
1617		numpages--;
1618	}
1619	return (count);
1620}
1621
1622static int
1623reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1624{
1625	struct bounce_zone *bz;
1626	int pages;
1627
1628	mtx_assert(&bounce_lock, MA_OWNED);
1629	bz = dmat->bounce_zone;
1630	pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1631	if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1632		return (map->pagesneeded - (map->pagesreserved + pages));
1633	bz->free_bpages -= pages;
1634	bz->reserved_bpages += pages;
1635	map->pagesreserved += pages;
1636	pages = map->pagesneeded - map->pagesreserved;
1637
1638	return (pages);
1639}
1640
1641static bus_addr_t
1642add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1643    bus_addr_t addr, bus_size_t size)
1644{
1645	struct bounce_zone *bz;
1646	struct bounce_page *bpage;
1647
1648	KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1649	KASSERT(map != NULL, ("add_bounce_page: bad map %p", map));
1650
1651	bz = dmat->bounce_zone;
1652	if (map->pagesneeded == 0)
1653		panic("add_bounce_page: map doesn't need any pages");
1654	map->pagesneeded--;
1655
1656	if (map->pagesreserved == 0)
1657		panic("add_bounce_page: map doesn't need any pages");
1658	map->pagesreserved--;
1659
1660	mtx_lock(&bounce_lock);
1661	bpage = STAILQ_FIRST(&bz->bounce_page_list);
1662	if (bpage == NULL)
1663		panic("add_bounce_page: free page list is empty");
1664
1665	STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1666	bz->reserved_bpages--;
1667	bz->active_bpages++;
1668	mtx_unlock(&bounce_lock);
1669
1670	if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1671		/* Page offset needs to be preserved. */
1672		bpage->vaddr |= addr & PAGE_MASK;
1673		bpage->busaddr |= addr & PAGE_MASK;
1674	}
1675	bpage->datavaddr = vaddr;
1676	bpage->datapage = PHYS_TO_VM_PAGE(addr);
1677	bpage->dataoffs = addr & PAGE_MASK;
1678	bpage->datacount = size;
1679	STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1680	return (bpage->busaddr);
1681}
1682
1683static void
1684free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1685{
1686	struct bus_dmamap *map;
1687	struct bounce_zone *bz;
1688
1689	bz = dmat->bounce_zone;
1690	bpage->datavaddr = 0;
1691	bpage->datacount = 0;
1692	if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1693		/*
1694		 * Reset the bounce page to start at offset 0.  Other uses
1695		 * of this bounce page may need to store a full page of
1696		 * data and/or assume it starts on a page boundary.
1697		 */
1698		bpage->vaddr &= ~PAGE_MASK;
1699		bpage->busaddr &= ~PAGE_MASK;
1700	}
1701
1702	mtx_lock(&bounce_lock);
1703	STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1704	bz->free_bpages++;
1705	bz->active_bpages--;
1706	if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1707		if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1708			STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1709			STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1710			    map, links);
1711			busdma_swi_pending = 1;
1712			bz->total_deferred++;
1713			swi_sched(vm_ih, 0);
1714		}
1715	}
1716	mtx_unlock(&bounce_lock);
1717}
1718
1719void
1720busdma_swi(void)
1721{
1722	bus_dma_tag_t dmat;
1723	struct bus_dmamap *map;
1724
1725	mtx_lock(&bounce_lock);
1726	while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1727		STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1728		mtx_unlock(&bounce_lock);
1729		dmat = map->dmat;
1730		dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_LOCK);
1731		bus_dmamap_load_mem(map->dmat, map, &map->mem, map->callback,
1732		    map->callback_arg, BUS_DMA_WAITOK);
1733		dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_UNLOCK);
1734		mtx_lock(&bounce_lock);
1735	}
1736	mtx_unlock(&bounce_lock);
1737}
1738