1239268Sgonzo/*-
2289865Sian * Copyright (c) 2012-2015 Ian Lepore
3239268Sgonzo * Copyright (c) 2010 Mark Tinguely
4239268Sgonzo * Copyright (c) 2004 Olivier Houchard
5239268Sgonzo * Copyright (c) 2002 Peter Grehan
6239268Sgonzo * Copyright (c) 1997, 1998 Justin T. Gibbs.
7239268Sgonzo * All rights reserved.
8239268Sgonzo *
9239268Sgonzo * Redistribution and use in source and binary forms, with or without
10239268Sgonzo * modification, are permitted provided that the following conditions
11239268Sgonzo * are met:
12239268Sgonzo * 1. Redistributions of source code must retain the above copyright
13239268Sgonzo *    notice, this list of conditions, and the following disclaimer,
14239268Sgonzo *    without modification, immediately at the beginning of the file.
15239268Sgonzo * 2. The name of the author may not be used to endorse or promote products
16239268Sgonzo *    derived from this software without specific prior written permission.
17239268Sgonzo *
18239268Sgonzo * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19239268Sgonzo * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20239268Sgonzo * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21239268Sgonzo * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
22239268Sgonzo * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23239268Sgonzo * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24239268Sgonzo * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25239268Sgonzo * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26239268Sgonzo * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27239268Sgonzo * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28239268Sgonzo * SUCH DAMAGE.
29239268Sgonzo *
30239268Sgonzo *  From i386/busdma_machdep.c 191438 2009-04-23 20:24:19Z jhb
31239268Sgonzo */
32239268Sgonzo
33239268Sgonzo#include <sys/cdefs.h>
34239268Sgonzo__FBSDID("$FreeBSD: stable/11/sys/arm/arm/busdma_machdep-v6.c 318976 2017-05-27 07:47:52Z hselasky $");
35239268Sgonzo
36239268Sgonzo#include <sys/param.h>
37239268Sgonzo#include <sys/systm.h>
38239268Sgonzo#include <sys/malloc.h>
39239268Sgonzo#include <sys/bus.h>
40244469Scognet#include <sys/busdma_bufalloc.h>
41269321Sian#include <sys/counter.h>
42239268Sgonzo#include <sys/interrupt.h>
43239268Sgonzo#include <sys/kernel.h>
44239268Sgonzo#include <sys/ktr.h>
45239268Sgonzo#include <sys/lock.h>
46246713Skib#include <sys/memdesc.h>
47239268Sgonzo#include <sys/proc.h>
48239268Sgonzo#include <sys/mutex.h>
49246713Skib#include <sys/sysctl.h>
50239268Sgonzo#include <sys/uio.h>
51239268Sgonzo
52239268Sgonzo#include <vm/vm.h>
53239268Sgonzo#include <vm/vm_page.h>
54239268Sgonzo#include <vm/vm_map.h>
55244469Scognet#include <vm/vm_extern.h>
56244469Scognet#include <vm/vm_kern.h>
57239268Sgonzo
58239268Sgonzo#include <machine/atomic.h>
59239268Sgonzo#include <machine/bus.h>
60289759Sjah#include <machine/cpu-v6.h>
61239268Sgonzo#include <machine/md_var.h>
62239268Sgonzo
63289893Sian#define	BUSDMA_DCACHE_ALIGN	cpuinfo.dcache_line_size
64289893Sian#define	BUSDMA_DCACHE_MASK	cpuinfo.dcache_line_mask
65289893Sian
66289851Sian#define	MAX_BPAGES		64
67289851Sian#define	MAX_DMA_SEGMENTS	4096
68289851Sian#define	BUS_DMA_EXCL_BOUNCE	BUS_DMA_BUS2
69289851Sian#define	BUS_DMA_ALIGN_BOUNCE	BUS_DMA_BUS3
70289851Sian#define	BUS_DMA_COULD_BOUNCE	(BUS_DMA_EXCL_BOUNCE | BUS_DMA_ALIGN_BOUNCE)
71289851Sian#define	BUS_DMA_MIN_ALLOC_COMP	BUS_DMA_BUS4
72239268Sgonzo
73239268Sgonzostruct bounce_zone;
74239268Sgonzo
75239268Sgonzostruct bus_dma_tag {
76289851Sian	bus_dma_tag_t		parent;
77289851Sian	bus_size_t		alignment;
78289854Sian	bus_addr_t		boundary;
79289851Sian	bus_addr_t		lowaddr;
80289851Sian	bus_addr_t		highaddr;
81289851Sian	bus_dma_filter_t	*filter;
82289851Sian	void			*filterarg;
83289851Sian	bus_size_t		maxsize;
84289851Sian	u_int			nsegments;
85289851Sian	bus_size_t		maxsegsz;
86289851Sian	int			flags;
87289851Sian	int			ref_count;
88289851Sian	int			map_count;
89289851Sian	bus_dma_lock_t		*lockfunc;
90289851Sian	void			*lockfuncarg;
91289851Sian	struct bounce_zone	*bounce_zone;
92239268Sgonzo};
93239268Sgonzo
94239268Sgonzostruct bounce_page {
95239268Sgonzo	vm_offset_t	vaddr;		/* kva of bounce buffer */
96239268Sgonzo	bus_addr_t	busaddr;	/* Physical address */
97239268Sgonzo	vm_offset_t	datavaddr;	/* kva of client data */
98289759Sjah	vm_page_t	datapage;	/* physical page of client data */
99289759Sjah	vm_offset_t	dataoffs;	/* page offset of client data */
100239268Sgonzo	bus_size_t	datacount;	/* client data count */
101239268Sgonzo	STAILQ_ENTRY(bounce_page) links;
102239268Sgonzo};
103239268Sgonzo
104239268Sgonzostruct sync_list {
105286968Sian	vm_offset_t	vaddr;		/* kva of client data */
106291018Smmel	bus_addr_t	paddr;		/* physical address */
107289759Sjah	vm_page_t	pages;		/* starting page of client data */
108239268Sgonzo	bus_size_t	datacount;	/* client data count */
109239268Sgonzo};
110239268Sgonzo
111239268Sgonzoint busdma_swi_pending;
112239268Sgonzo
113239268Sgonzostruct bounce_zone {
114239268Sgonzo	STAILQ_ENTRY(bounce_zone) links;
115239268Sgonzo	STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
116239268Sgonzo	int		total_bpages;
117239268Sgonzo	int		free_bpages;
118239268Sgonzo	int		reserved_bpages;
119239268Sgonzo	int		active_bpages;
120239268Sgonzo	int		total_bounced;
121239268Sgonzo	int		total_deferred;
122239268Sgonzo	int		map_count;
123239268Sgonzo	bus_size_t	alignment;
124239268Sgonzo	bus_addr_t	lowaddr;
125239268Sgonzo	char		zoneid[8];
126239268Sgonzo	char		lowaddrid[20];
127239268Sgonzo	struct sysctl_ctx_list sysctl_tree;
128239268Sgonzo	struct sysctl_oid *sysctl_tree_top;
129239268Sgonzo};
130239268Sgonzo
131239268Sgonzostatic struct mtx bounce_lock;
132239268Sgonzostatic int total_bpages;
133239268Sgonzostatic int busdma_zonecount;
134269217Sianstatic uint32_t tags_total;
135269217Sianstatic uint32_t maps_total;
136269217Sianstatic uint32_t maps_dmamem;
137269217Sianstatic uint32_t maps_coherent;
138269321Sianstatic counter_u64_t maploads_total;
139269321Sianstatic counter_u64_t maploads_bounced;
140269321Sianstatic counter_u64_t maploads_coherent;
141269321Sianstatic counter_u64_t maploads_dmamem;
142269321Sianstatic counter_u64_t maploads_mbuf;
143269321Sianstatic counter_u64_t maploads_physmem;
144269217Sian
145239268Sgonzostatic STAILQ_HEAD(, bounce_zone) bounce_zone_list;
146239268Sgonzo
147239268SgonzoSYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
148269217SianSYSCTL_UINT(_hw_busdma, OID_AUTO, tags_total, CTLFLAG_RD, &tags_total, 0,
149269321Sian   "Number of active tags");
150269217SianSYSCTL_UINT(_hw_busdma, OID_AUTO, maps_total, CTLFLAG_RD, &maps_total, 0,
151269321Sian   "Number of active maps");
152269217SianSYSCTL_UINT(_hw_busdma, OID_AUTO, maps_dmamem, CTLFLAG_RD, &maps_dmamem, 0,
153269321Sian   "Number of active maps for bus_dmamem_alloc buffers");
154269217SianSYSCTL_UINT(_hw_busdma, OID_AUTO, maps_coherent, CTLFLAG_RD, &maps_coherent, 0,
155269321Sian   "Number of active maps with BUS_DMA_COHERENT flag set");
156283366SandrewSYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_total, CTLFLAG_RD,
157269321Sian    &maploads_total, "Number of load operations performed");
158269321SianSYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_bounced, CTLFLAG_RD,
159269321Sian    &maploads_bounced, "Number of load operations that used bounce buffers");
160269321SianSYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_coherent, CTLFLAG_RD,
161269321Sian    &maploads_dmamem, "Number of load operations on BUS_DMA_COHERENT memory");
162269321SianSYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_dmamem, CTLFLAG_RD,
163269321Sian    &maploads_dmamem, "Number of load operations on bus_dmamem_alloc buffers");
164269321SianSYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_mbuf, CTLFLAG_RD,
165269321Sian    &maploads_mbuf, "Number of load operations for mbufs");
166269321SianSYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_physmem, CTLFLAG_RD,
167269321Sian    &maploads_physmem, "Number of load operations on physical buffers");
168239268SgonzoSYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bpages, 0,
169269321Sian   "Total bounce pages");
170239268Sgonzo
171239268Sgonzostruct bus_dmamap {
172289851Sian	struct bp_list		bpages;
173289851Sian	int			pagesneeded;
174289851Sian	int			pagesreserved;
175289851Sian	bus_dma_tag_t		dmat;
176289851Sian	struct memdesc		mem;
177289851Sian	bus_dmamap_callback_t	*callback;
178289851Sian	void			*callback_arg;
179289851Sian	int			flags;
180289851Sian#define	DMAMAP_COHERENT		(1 << 0)
181289851Sian#define	DMAMAP_DMAMEM_ALLOC	(1 << 1)
182289851Sian#define	DMAMAP_MBUF		(1 << 2)
183239268Sgonzo	STAILQ_ENTRY(bus_dmamap) links;
184269216Sian	bus_dma_segment_t	*segments;
185289851Sian	int			sync_count;
186289851Sian	struct sync_list	slist[];
187239268Sgonzo};
188239268Sgonzo
189239268Sgonzostatic STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
190239268Sgonzostatic STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist;
191239268Sgonzo
192239268Sgonzostatic void init_bounce_pages(void *dummy);
193239268Sgonzostatic int alloc_bounce_zone(bus_dma_tag_t dmat);
194239268Sgonzostatic int alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages);
195239268Sgonzostatic int reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
196289851Sian    int commit);
197239268Sgonzostatic bus_addr_t add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map,
198289851Sian    vm_offset_t vaddr, bus_addr_t addr, bus_size_t size);
199239268Sgonzostatic void free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage);
200289759Sjahstatic void _bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap,
201289759Sjah    bus_dmamap_t map, void *buf, bus_size_t buflen, int flags);
202246713Skibstatic void _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map,
203246713Skib    vm_paddr_t buf, bus_size_t buflen, int flags);
204246713Skibstatic int _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
205246713Skib    int flags);
206289759Sjahstatic void dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size);
207289759Sjahstatic void dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op);
208239268Sgonzo
209244469Scognetstatic busdma_bufalloc_t coherent_allocator;	/* Cache of coherent buffers */
210244469Scognetstatic busdma_bufalloc_t standard_allocator;	/* Cache of standard buffers */
211289858Sian
212289858SianMALLOC_DEFINE(M_BUSDMA, "busdma", "busdma metadata");
213289858SianMALLOC_DEFINE(M_BOUNCE, "bounce", "busdma bounce pages");
214289858Sian
215244469Scognetstatic void
216244469Scognetbusdma_init(void *dummy)
217244469Scognet{
218252652Sgonzo	int uma_flags;
219244469Scognet
220269321Sian	maploads_total    = counter_u64_alloc(M_WAITOK);
221269321Sian	maploads_bounced  = counter_u64_alloc(M_WAITOK);
222269321Sian	maploads_coherent = counter_u64_alloc(M_WAITOK);
223269321Sian	maploads_dmamem   = counter_u64_alloc(M_WAITOK);
224269321Sian	maploads_mbuf     = counter_u64_alloc(M_WAITOK);
225269321Sian	maploads_physmem  = counter_u64_alloc(M_WAITOK);
226269321Sian
227252652Sgonzo	uma_flags = 0;
228252652Sgonzo
229244469Scognet	/* Create a cache of buffers in standard (cacheable) memory. */
230283366Sandrew	standard_allocator = busdma_bufalloc_create("buffer",
231289893Sian	    BUSDMA_DCACHE_ALIGN,/* minimum_alignment */
232283366Sandrew	    NULL,		/* uma_alloc func */
233244469Scognet	    NULL,		/* uma_free func */
234252652Sgonzo	    uma_flags);		/* uma_zcreate_flags */
235244469Scognet
236252652Sgonzo#ifdef INVARIANTS
237283366Sandrew	/*
238252652Sgonzo	 * Force UMA zone to allocate service structures like
239252652Sgonzo	 * slabs using own allocator. uma_debug code performs
240252652Sgonzo	 * atomic ops on uma_slab_t fields and safety of this
241252652Sgonzo	 * operation is not guaranteed for write-back caches
242252652Sgonzo	 */
243252652Sgonzo	uma_flags = UMA_ZONE_OFFPAGE;
244252652Sgonzo#endif
245244469Scognet	/*
246244469Scognet	 * Create a cache of buffers in uncacheable memory, to implement the
247244469Scognet	 * BUS_DMA_COHERENT (and potentially BUS_DMA_NOCACHE) flag.
248244469Scognet	 */
249244469Scognet	coherent_allocator = busdma_bufalloc_create("coherent",
250289893Sian	    BUSDMA_DCACHE_ALIGN,/* minimum_alignment */
251283366Sandrew	    busdma_bufalloc_alloc_uncacheable,
252283366Sandrew	    busdma_bufalloc_free_uncacheable,
253252652Sgonzo	    uma_flags);	/* uma_zcreate_flags */
254244469Scognet}
255244469Scognet
256244469Scognet/*
257244469Scognet * This init historically used SI_SUB_VM, but now the init code requires
258289858Sian * malloc(9) using M_BUSDMA memory and the pcpu zones for counter(9), which get
259269321Sian * set up by SI_SUB_KMEM and SI_ORDER_LAST, so we'll go right after that by
260269321Sian * using SI_SUB_KMEM+1.
261244469Scognet */
262269321SianSYSINIT(busdma, SI_SUB_KMEM+1, SI_ORDER_FIRST, busdma_init, NULL);
263244469Scognet
264269136Sian/*
265269136Sian * This routine checks the exclusion zone constraints from a tag against the
266269136Sian * physical RAM available on the machine.  If a tag specifies an exclusion zone
267269136Sian * but there's no RAM in that zone, then we avoid allocating resources to bounce
268269136Sian * a request, and we can use any memory allocator (as opposed to needing
269269136Sian * kmem_alloc_contig() just because it can allocate pages in an address range).
270269136Sian *
271269136Sian * Most tags have BUS_SPACE_MAXADDR or BUS_SPACE_MAXADDR_32BIT (they are the
272269136Sian * same value on 32-bit architectures) as their lowaddr constraint, and we can't
273269136Sian * possibly have RAM at an address higher than the highest address we can
274269136Sian * express, so we take a fast out.
275269136Sian */
276269206Sianstatic int
277269207Sianexclusion_bounce_check(vm_offset_t lowaddr, vm_offset_t highaddr)
278239268Sgonzo{
279239268Sgonzo	int i;
280269136Sian
281269136Sian	if (lowaddr >= BUS_SPACE_MAXADDR)
282269136Sian		return (0);
283269136Sian
284239268Sgonzo	for (i = 0; phys_avail[i] && phys_avail[i + 1]; i += 2) {
285269209Sian		if ((lowaddr >= phys_avail[i] && lowaddr < phys_avail[i + 1]) ||
286269209Sian		    (lowaddr < phys_avail[i] && highaddr >= phys_avail[i]))
287239268Sgonzo			return (1);
288239268Sgonzo	}
289239268Sgonzo	return (0);
290239268Sgonzo}
291239268Sgonzo
292269206Sian/*
293269207Sian * Return true if the tag has an exclusion zone that could lead to bouncing.
294269207Sian */
295269207Sianstatic __inline int
296269207Sianexclusion_bounce(bus_dma_tag_t dmat)
297269207Sian{
298269207Sian
299269207Sian	return (dmat->flags & BUS_DMA_EXCL_BOUNCE);
300269207Sian}
301269207Sian
302269207Sian/*
303269206Sian * Return true if the given address does not fall on the alignment boundary.
304269206Sian */
305269206Sianstatic __inline int
306269206Sianalignment_bounce(bus_dma_tag_t dmat, bus_addr_t addr)
307269206Sian{
308269206Sian
309269206Sian	return (addr & (dmat->alignment - 1));
310269206Sian}
311269206Sian
312269206Sian/*
313269212Sian * Return true if the DMA should bounce because the start or end does not fall
314269212Sian * on a cacheline boundary (which would require a partial cacheline flush).
315269212Sian * COHERENT memory doesn't trigger cacheline flushes.  Memory allocated by
316269212Sian * bus_dmamem_alloc() is always aligned to cacheline boundaries, and there's a
317269212Sian * strict rule that such memory cannot be accessed by the CPU while DMA is in
318269212Sian * progress (or by multiple DMA engines at once), so that it's always safe to do
319269212Sian * full cacheline flushes even if that affects memory outside the range of a
320269212Sian * given DMA operation that doesn't involve the full allocated buffer.  If we're
321269212Sian * mapping an mbuf, that follows the same rules as a buffer we allocated.
322269206Sian */
323269206Sianstatic __inline int
324269212Siancacheline_bounce(bus_dmamap_t map, bus_addr_t addr, bus_size_t size)
325269206Sian{
326269206Sian
327269212Sian	if (map->flags & (DMAMAP_DMAMEM_ALLOC | DMAMAP_COHERENT | DMAMAP_MBUF))
328269212Sian		return (0);
329307345Smmel	return ((addr | size) & BUSDMA_DCACHE_MASK);
330269206Sian}
331269206Sian
332269211Sian/*
333269211Sian * Return true if we might need to bounce the DMA described by addr and size.
334269211Sian *
335269211Sian * This is used to quick-check whether we need to do the more expensive work of
336269211Sian * checking the DMA page-by-page looking for alignment and exclusion bounces.
337269211Sian *
338269211Sian * Note that the addr argument might be either virtual or physical.  It doesn't
339269211Sian * matter because we only look at the low-order bits, which are the same in both
340269211Sian * address spaces.
341269211Sian */
342269211Sianstatic __inline int
343283366Sandrewmight_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t addr,
344269211Sian    bus_size_t size)
345269211Sian{
346274545Sian
347269212Sian	return ((dmat->flags & BUS_DMA_EXCL_BOUNCE) ||
348269212Sian	    alignment_bounce(dmat, addr) ||
349269212Sian	    cacheline_bounce(map, addr, size));
350269211Sian}
351269211Sian
352269211Sian/*
353269211Sian * Return true if we must bounce the DMA described by paddr and size.
354269211Sian *
355269211Sian * Bouncing can be triggered by DMA that doesn't begin and end on cacheline
356269211Sian * boundaries, or doesn't begin on an alignment boundary, or falls within the
357269211Sian * exclusion zone of any tag in the ancestry chain.
358269211Sian *
359269211Sian * For exclusions, walk the chain of tags comparing paddr to the exclusion zone
360269211Sian * within each tag.  If the tag has a filter function, use it to decide whether
361269211Sian * the DMA needs to bounce, otherwise any DMA within the zone bounces.
362269211Sian */
363269211Sianstatic int
364283366Sandrewmust_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t paddr,
365269211Sian    bus_size_t size)
366269211Sian{
367269211Sian
368269212Sian	if (cacheline_bounce(map, paddr, size))
369269211Sian		return (1);
370269211Sian
371269211Sian	/*
372269211Sian	 *  The tag already contains ancestors' alignment restrictions so this
373269211Sian	 *  check doesn't need to be inside the loop.
374269211Sian	 */
375269211Sian	if (alignment_bounce(dmat, paddr))
376269211Sian		return (1);
377269211Sian
378269211Sian	/*
379269211Sian	 * Even though each tag has an exclusion zone that is a superset of its
380269211Sian	 * own and all its ancestors' exclusions, the exclusion zone of each tag
381269211Sian	 * up the chain must be checked within the loop, because the busdma
382269211Sian	 * rules say the filter function is called only when the address lies
383269211Sian	 * within the low-highaddr range of the tag that filterfunc belongs to.
384269211Sian	 */
385269211Sian	while (dmat != NULL && exclusion_bounce(dmat)) {
386269211Sian		if ((paddr >= dmat->lowaddr && paddr <= dmat->highaddr) &&
387283366Sandrew		    (dmat->filter == NULL ||
388269211Sian		    dmat->filter(dmat->filterarg, paddr) != 0))
389269211Sian			return (1);
390269211Sian		dmat = dmat->parent;
391283366Sandrew	}
392269211Sian
393269211Sian	return (0);
394269211Sian}
395269211Sian
396239268Sgonzo/*
397239268Sgonzo * Convenience function for manipulating driver locks from busdma (during
398239268Sgonzo * busdma_swi, for example).  Drivers that don't provide their own locks
399239268Sgonzo * should specify &Giant to dmat->lockfuncarg.  Drivers that use their own
400239268Sgonzo * non-mutex locking scheme don't have to use this at all.
401239268Sgonzo */
402239268Sgonzovoid
403239268Sgonzobusdma_lock_mutex(void *arg, bus_dma_lock_op_t op)
404239268Sgonzo{
405239268Sgonzo	struct mtx *dmtx;
406239268Sgonzo
407239268Sgonzo	dmtx = (struct mtx *)arg;
408239268Sgonzo	switch (op) {
409239268Sgonzo	case BUS_DMA_LOCK:
410239268Sgonzo		mtx_lock(dmtx);
411239268Sgonzo		break;
412239268Sgonzo	case BUS_DMA_UNLOCK:
413239268Sgonzo		mtx_unlock(dmtx);
414239268Sgonzo		break;
415239268Sgonzo	default:
416239268Sgonzo		panic("Unknown operation 0x%x for busdma_lock_mutex!", op);
417239268Sgonzo	}
418239268Sgonzo}
419239268Sgonzo
420239268Sgonzo/*
421239268Sgonzo * dflt_lock should never get called.  It gets put into the dma tag when
422239268Sgonzo * lockfunc == NULL, which is only valid if the maps that are associated
423239268Sgonzo * with the tag are meant to never be defered.
424239268Sgonzo * XXX Should have a way to identify which driver is responsible here.
425239268Sgonzo */
426239268Sgonzostatic void
427239268Sgonzodflt_lock(void *arg, bus_dma_lock_op_t op)
428239268Sgonzo{
429274545Sian
430239268Sgonzo	panic("driver error: busdma dflt_lock called");
431239268Sgonzo}
432239268Sgonzo
433239268Sgonzo/*
434239268Sgonzo * Allocate a device specific dma_tag.
435239268Sgonzo */
436239268Sgonzoint
437239268Sgonzobus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
438289854Sian    bus_addr_t boundary, bus_addr_t lowaddr, bus_addr_t highaddr,
439289851Sian    bus_dma_filter_t *filter, void *filterarg, bus_size_t maxsize,
440289851Sian    int nsegments, bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
441289851Sian    void *lockfuncarg, bus_dma_tag_t *dmat)
442239268Sgonzo{
443239268Sgonzo	bus_dma_tag_t newtag;
444239268Sgonzo	int error = 0;
445239268Sgonzo
446274191Sian	/* Basic sanity checking. */
447274536Sian	KASSERT(boundary == 0 || powerof2(boundary),
448274191Sian	    ("dma tag boundary %lu, must be a power of 2", boundary));
449274191Sian	KASSERT(boundary == 0 || boundary >= maxsegsz,
450274191Sian	    ("dma tag boundary %lu is < maxsegsz %lu\n", boundary, maxsegsz));
451274536Sian	KASSERT(alignment != 0 && powerof2(alignment),
452274191Sian	    ("dma tag alignment %lu, must be non-zero power of 2", alignment));
453274191Sian	KASSERT(maxsegsz != 0, ("dma tag maxsegsz must not be zero"));
454239268Sgonzo
455239268Sgonzo	/* Return a NULL tag on failure */
456239268Sgonzo	*dmat = NULL;
457239268Sgonzo
458289858Sian	newtag = (bus_dma_tag_t)malloc(sizeof(*newtag), M_BUSDMA,
459239268Sgonzo	    M_ZERO | M_NOWAIT);
460239268Sgonzo	if (newtag == NULL) {
461239268Sgonzo		CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
462239268Sgonzo		    __func__, newtag, 0, error);
463239268Sgonzo		return (ENOMEM);
464239268Sgonzo	}
465239268Sgonzo
466239268Sgonzo	newtag->parent = parent;
467239268Sgonzo	newtag->alignment = alignment;
468239268Sgonzo	newtag->boundary = boundary;
469239268Sgonzo	newtag->lowaddr = trunc_page((vm_paddr_t)lowaddr) + (PAGE_SIZE - 1);
470239268Sgonzo	newtag->highaddr = trunc_page((vm_paddr_t)highaddr) +
471239268Sgonzo	    (PAGE_SIZE - 1);
472239268Sgonzo	newtag->filter = filter;
473239268Sgonzo	newtag->filterarg = filterarg;
474239268Sgonzo	newtag->maxsize = maxsize;
475239268Sgonzo	newtag->nsegments = nsegments;
476239268Sgonzo	newtag->maxsegsz = maxsegsz;
477239268Sgonzo	newtag->flags = flags;
478239268Sgonzo	newtag->ref_count = 1; /* Count ourself */
479239268Sgonzo	newtag->map_count = 0;
480239268Sgonzo	if (lockfunc != NULL) {
481239268Sgonzo		newtag->lockfunc = lockfunc;
482239268Sgonzo		newtag->lockfuncarg = lockfuncarg;
483239268Sgonzo	} else {
484239268Sgonzo		newtag->lockfunc = dflt_lock;
485239268Sgonzo		newtag->lockfuncarg = NULL;
486239268Sgonzo	}
487239268Sgonzo
488239268Sgonzo	/* Take into account any restrictions imposed by our parent tag */
489239268Sgonzo	if (parent != NULL) {
490239268Sgonzo		newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
491239268Sgonzo		newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
492269210Sian		newtag->alignment = MAX(parent->alignment, newtag->alignment);
493269207Sian		newtag->flags |= parent->flags & BUS_DMA_COULD_BOUNCE;
494239268Sgonzo		if (newtag->boundary == 0)
495239268Sgonzo			newtag->boundary = parent->boundary;
496239268Sgonzo		else if (parent->boundary != 0)
497239268Sgonzo			newtag->boundary = MIN(parent->boundary,
498239268Sgonzo					       newtag->boundary);
499239268Sgonzo		if (newtag->filter == NULL) {
500239268Sgonzo			/*
501269207Sian			 * Short circuit to looking at our parent directly
502239268Sgonzo			 * since we have encapsulated all of its information
503239268Sgonzo			 */
504239268Sgonzo			newtag->filter = parent->filter;
505239268Sgonzo			newtag->filterarg = parent->filterarg;
506239268Sgonzo			newtag->parent = parent->parent;
507239268Sgonzo		}
508239268Sgonzo		if (newtag->parent != NULL)
509239268Sgonzo			atomic_add_int(&parent->ref_count, 1);
510239268Sgonzo	}
511239268Sgonzo
512269207Sian	if (exclusion_bounce_check(newtag->lowaddr, newtag->highaddr))
513269207Sian		newtag->flags |= BUS_DMA_EXCL_BOUNCE;
514269207Sian	if (alignment_bounce(newtag, 1))
515269207Sian		newtag->flags |= BUS_DMA_ALIGN_BOUNCE;
516239268Sgonzo
517256637Sian	/*
518256637Sian	 * Any request can auto-bounce due to cacheline alignment, in addition
519256637Sian	 * to any alignment or boundary specifications in the tag, so if the
520256637Sian	 * ALLOCNOW flag is set, there's always work to do.
521256637Sian	 */
522254061Scognet	if ((flags & BUS_DMA_ALLOCNOW) != 0) {
523239268Sgonzo		struct bounce_zone *bz;
524256637Sian		/*
525256637Sian		 * Round size up to a full page, and add one more page because
526256637Sian		 * there can always be one more boundary crossing than the
527256637Sian		 * number of pages in a transfer.
528256637Sian		 */
529256637Sian		maxsize = roundup2(maxsize, PAGE_SIZE) + PAGE_SIZE;
530283366Sandrew
531239268Sgonzo		if ((error = alloc_bounce_zone(newtag)) != 0) {
532289858Sian			free(newtag, M_BUSDMA);
533239268Sgonzo			return (error);
534239268Sgonzo		}
535239268Sgonzo		bz = newtag->bounce_zone;
536239268Sgonzo
537239268Sgonzo		if (ptoa(bz->total_bpages) < maxsize) {
538239268Sgonzo			int pages;
539239268Sgonzo
540239268Sgonzo			pages = atop(maxsize) - bz->total_bpages;
541239268Sgonzo
542239268Sgonzo			/* Add pages to our bounce pool */
543239268Sgonzo			if (alloc_bounce_pages(newtag, pages) < pages)
544239268Sgonzo				error = ENOMEM;
545239268Sgonzo		}
546239268Sgonzo		/* Performed initial allocation */
547239268Sgonzo		newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
548239268Sgonzo	} else
549239268Sgonzo		newtag->bounce_zone = NULL;
550239268Sgonzo
551239268Sgonzo	if (error != 0) {
552289858Sian		free(newtag, M_BUSDMA);
553239268Sgonzo	} else {
554269217Sian		atomic_add_32(&tags_total, 1);
555239268Sgonzo		*dmat = newtag;
556239268Sgonzo	}
557239268Sgonzo	CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
558239268Sgonzo	    __func__, newtag, (newtag != NULL ? newtag->flags : 0), error);
559239268Sgonzo	return (error);
560239268Sgonzo}
561239268Sgonzo
562239268Sgonzoint
563239268Sgonzobus_dma_tag_destroy(bus_dma_tag_t dmat)
564239268Sgonzo{
565239268Sgonzo	bus_dma_tag_t dmat_copy;
566239268Sgonzo	int error;
567239268Sgonzo
568239268Sgonzo	error = 0;
569239268Sgonzo	dmat_copy = dmat;
570239268Sgonzo
571239268Sgonzo	if (dmat != NULL) {
572239268Sgonzo
573239268Sgonzo		if (dmat->map_count != 0) {
574239268Sgonzo			error = EBUSY;
575239268Sgonzo			goto out;
576239268Sgonzo		}
577239268Sgonzo
578239268Sgonzo		while (dmat != NULL) {
579239268Sgonzo			bus_dma_tag_t parent;
580239268Sgonzo
581239268Sgonzo			parent = dmat->parent;
582239268Sgonzo			atomic_subtract_int(&dmat->ref_count, 1);
583239268Sgonzo			if (dmat->ref_count == 0) {
584269217Sian				atomic_subtract_32(&tags_total, 1);
585289858Sian				free(dmat, M_BUSDMA);
586239268Sgonzo				/*
587239268Sgonzo				 * Last reference count, so
588239268Sgonzo				 * release our reference
589239268Sgonzo				 * count on our parent.
590239268Sgonzo				 */
591239268Sgonzo				dmat = parent;
592239268Sgonzo			} else
593239268Sgonzo				dmat = NULL;
594239268Sgonzo		}
595239268Sgonzo	}
596239268Sgonzoout:
597239268Sgonzo	CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
598239268Sgonzo	return (error);
599239268Sgonzo}
600239268Sgonzo
601286968Sianstatic int
602286968Sianallocate_bz_and_pages(bus_dma_tag_t dmat, bus_dmamap_t mapp)
603254061Scognet{
604274545Sian	struct bounce_zone *bz;
605254061Scognet	int maxpages;
606254061Scognet	int error;
607283366Sandrew
608254061Scognet	if (dmat->bounce_zone == NULL)
609254061Scognet		if ((error = alloc_bounce_zone(dmat)) != 0)
610254061Scognet			return (error);
611254061Scognet	bz = dmat->bounce_zone;
612254061Scognet	/* Initialize the new map */
613254061Scognet	STAILQ_INIT(&(mapp->bpages));
614254061Scognet
615254061Scognet	/*
616256637Sian	 * Attempt to add pages to our pool on a per-instance basis up to a sane
617256637Sian	 * limit.  Even if the tag isn't flagged as COULD_BOUNCE due to
618256637Sian	 * alignment and boundary constraints, it could still auto-bounce due to
619256637Sian	 * cacheline alignment, which requires at most two bounce pages.
620254061Scognet	 */
621254229Scognet	if (dmat->flags & BUS_DMA_COULD_BOUNCE)
622254229Scognet		maxpages = MAX_BPAGES;
623254229Scognet	else
624256637Sian		maxpages = 2 * bz->map_count;
625291193Sskra	if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0 ||
626291193Sskra	    (bz->map_count > 0 && bz->total_bpages < maxpages)) {
627254061Scognet		int pages;
628283366Sandrew
629256637Sian		pages = atop(roundup2(dmat->maxsize, PAGE_SIZE)) + 1;
630254061Scognet		pages = MIN(maxpages - bz->total_bpages, pages);
631256637Sian		pages = MAX(pages, 2);
632254061Scognet		if (alloc_bounce_pages(dmat, pages) < pages)
633254061Scognet			return (ENOMEM);
634283366Sandrew
635254061Scognet		if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0)
636254061Scognet			dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
637254061Scognet	}
638254061Scognet	bz->map_count++;
639254061Scognet	return (0);
640254061Scognet}
641254061Scognet
642269216Sianstatic bus_dmamap_t
643269216Sianallocate_map(bus_dma_tag_t dmat, int mflags)
644269216Sian{
645269216Sian	int mapsize, segsize;
646269216Sian	bus_dmamap_t map;
647269216Sian
648269216Sian	/*
649269216Sian	 * Allocate the map.  The map structure ends with an embedded
650269216Sian	 * variable-sized array of sync_list structures.  Following that
651269216Sian	 * we allocate enough extra space to hold the array of bus_dma_segments.
652269216Sian	 */
653283366Sandrew	KASSERT(dmat->nsegments <= MAX_DMA_SEGMENTS,
654269216Sian	   ("cannot allocate %u dma segments (max is %u)",
655269216Sian	    dmat->nsegments, MAX_DMA_SEGMENTS));
656269216Sian	segsize = sizeof(struct bus_dma_segment) * dmat->nsegments;
657269216Sian	mapsize = sizeof(*map) + sizeof(struct sync_list) * dmat->nsegments;
658289858Sian	map = malloc(mapsize + segsize, M_BUSDMA, mflags | M_ZERO);
659269216Sian	if (map == NULL) {
660269216Sian		CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
661269216Sian		return (NULL);
662269216Sian	}
663269216Sian	map->segments = (bus_dma_segment_t *)((uintptr_t)map + mapsize);
664269216Sian	return (map);
665269216Sian}
666269216Sian
667239268Sgonzo/*
668239268Sgonzo * Allocate a handle for mapping from kva/uva/physical
669239268Sgonzo * address space into bus device space.
670239268Sgonzo */
671239268Sgonzoint
672239268Sgonzobus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
673239268Sgonzo{
674269214Sian	bus_dmamap_t map;
675254061Scognet	int error = 0;
676239268Sgonzo
677269216Sian	*mapp = map = allocate_map(dmat, M_NOWAIT);
678269214Sian	if (map == NULL) {
679239268Sgonzo		CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
680239268Sgonzo		return (ENOMEM);
681239268Sgonzo	}
682239268Sgonzo
683239268Sgonzo	/*
684269216Sian	 * Bouncing might be required if the driver asks for an exclusion
685269216Sian	 * region, a data alignment that is stricter than 1, or DMA that begins
686269216Sian	 * or ends with a partial cacheline.  Whether bouncing will actually
687269216Sian	 * happen can't be known until mapping time, but we need to pre-allocate
688269216Sian	 * resources now because we might not be allowed to at mapping time.
689239268Sgonzo	 */
690269214Sian	error = allocate_bz_and_pages(dmat, map);
691254061Scognet	if (error != 0) {
692289858Sian		free(map, M_BUSDMA);
693254061Scognet		*mapp = NULL;
694254061Scognet		return (error);
695239268Sgonzo	}
696269217Sian	if (map->flags & DMAMAP_COHERENT)
697269217Sian		atomic_add_32(&maps_coherent, 1);
698269217Sian	atomic_add_32(&maps_total, 1);
699273599Sloos	dmat->map_count++;
700273599Sloos
701269217Sian	return (0);
702239268Sgonzo}
703239268Sgonzo
704239268Sgonzo/*
705239268Sgonzo * Destroy a handle for mapping from kva/uva/physical
706239268Sgonzo * address space into bus device space.
707239268Sgonzo */
708239268Sgonzoint
709239268Sgonzobus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
710239268Sgonzo{
711289865Sian
712246713Skib	if (STAILQ_FIRST(&map->bpages) != NULL || map->sync_count != 0) {
713239268Sgonzo		CTR3(KTR_BUSDMA, "%s: tag %p error %d",
714239268Sgonzo		    __func__, dmat, EBUSY);
715239268Sgonzo		return (EBUSY);
716239268Sgonzo	}
717239268Sgonzo	if (dmat->bounce_zone)
718239268Sgonzo		dmat->bounce_zone->map_count--;
719269217Sian	if (map->flags & DMAMAP_COHERENT)
720269217Sian		atomic_subtract_32(&maps_coherent, 1);
721269217Sian	atomic_subtract_32(&maps_total, 1);
722289858Sian	free(map, M_BUSDMA);
723239268Sgonzo	dmat->map_count--;
724239268Sgonzo	CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
725239268Sgonzo	return (0);
726239268Sgonzo}
727239268Sgonzo
728239268Sgonzo/*
729289865Sian * Allocate a piece of memory that can be efficiently mapped into bus device
730289865Sian * space based on the constraints listed in the dma tag.  Returns a pointer to
731289865Sian * the allocated memory, and a pointer to an associated bus_dmamap.
732239268Sgonzo */
733239268Sgonzoint
734289865Sianbus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
735289851Sian    bus_dmamap_t *mapp)
736239268Sgonzo{
737244469Scognet	busdma_bufalloc_t ba;
738244469Scognet	struct busdma_bufzone *bufzone;
739269214Sian	bus_dmamap_t map;
740244469Scognet	vm_memattr_t memattr;
741244469Scognet	int mflags;
742239268Sgonzo
743239268Sgonzo	if (flags & BUS_DMA_NOWAIT)
744239268Sgonzo		mflags = M_NOWAIT;
745239268Sgonzo	else
746239268Sgonzo		mflags = M_WAITOK;
747269216Sian	if (flags & BUS_DMA_ZERO)
748269216Sian		mflags |= M_ZERO;
749239268Sgonzo
750269216Sian	*mapp = map = allocate_map(dmat, mflags);
751269214Sian	if (map == NULL) {
752239268Sgonzo		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
753239268Sgonzo		    __func__, dmat, dmat->flags, ENOMEM);
754239268Sgonzo		return (ENOMEM);
755239268Sgonzo	}
756269214Sian	map->flags = DMAMAP_DMAMEM_ALLOC;
757239268Sgonzo
758269216Sian	/* Choose a busdma buffer allocator based on memory type flags. */
759244469Scognet	if (flags & BUS_DMA_COHERENT) {
760244469Scognet		memattr = VM_MEMATTR_UNCACHEABLE;
761244469Scognet		ba = coherent_allocator;
762269214Sian		map->flags |= DMAMAP_COHERENT;
763244469Scognet	} else {
764244469Scognet		memattr = VM_MEMATTR_DEFAULT;
765244469Scognet		ba = standard_allocator;
766244469Scognet	}
767239268Sgonzo
768244469Scognet	/*
769244469Scognet	 * Try to find a bufzone in the allocator that holds a cache of buffers
770244469Scognet	 * of the right size for this request.  If the buffer is too big to be
771244469Scognet	 * held in the allocator cache, this returns NULL.
772239268Sgonzo	 */
773244469Scognet	bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
774244469Scognet
775244469Scognet	/*
776244469Scognet	 * Allocate the buffer from the uma(9) allocator if...
777244469Scognet	 *  - It's small enough to be in the allocator (bufzone not NULL).
778244469Scognet	 *  - The alignment constraint isn't larger than the allocation size
779244469Scognet	 *    (the allocator aligns buffers to their size boundaries).
780244469Scognet	 *  - There's no need to handle lowaddr/highaddr exclusion zones.
781244469Scognet	 * else allocate non-contiguous pages if...
782318976Shselasky	 *  - The page count that could get allocated doesn't exceed
783318976Shselasky	 *    nsegments also when the maximum segment size is less
784318976Shselasky	 *    than PAGE_SIZE.
785244469Scognet	 *  - The alignment constraint isn't larger than a page boundary.
786244469Scognet	 *  - There are no boundary-crossing constraints.
787244469Scognet	 * else allocate a block of contiguous pages because one or more of the
788244469Scognet	 * constraints is something that only the contig allocator can fulfill.
789244469Scognet	 */
790244469Scognet	if (bufzone != NULL && dmat->alignment <= bufzone->size &&
791269207Sian	    !exclusion_bounce(dmat)) {
792244469Scognet		*vaddr = uma_zalloc(bufzone->umazone, mflags);
793318976Shselasky	} else if (dmat->nsegments >=
794318976Shselasky	    howmany(dmat->maxsize, MIN(dmat->maxsegsz, PAGE_SIZE)) &&
795318976Shselasky	    dmat->alignment <= PAGE_SIZE &&
796318976Shselasky	    (dmat->boundary % PAGE_SIZE) == 0) {
797254025Sjeff		*vaddr = (void *)kmem_alloc_attr(kernel_arena, dmat->maxsize,
798244469Scognet		    mflags, 0, dmat->lowaddr, memattr);
799239268Sgonzo	} else {
800254025Sjeff		*vaddr = (void *)kmem_alloc_contig(kernel_arena, dmat->maxsize,
801244469Scognet		    mflags, 0, dmat->lowaddr, dmat->alignment, dmat->boundary,
802244469Scognet		    memattr);
803239268Sgonzo	}
804239268Sgonzo	if (*vaddr == NULL) {
805239268Sgonzo		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
806239268Sgonzo		    __func__, dmat, dmat->flags, ENOMEM);
807289858Sian		free(map, M_BUSDMA);
808239268Sgonzo		*mapp = NULL;
809239268Sgonzo		return (ENOMEM);
810239268Sgonzo	}
811269217Sian	if (map->flags & DMAMAP_COHERENT)
812269217Sian		atomic_add_32(&maps_coherent, 1);
813269217Sian	atomic_add_32(&maps_dmamem, 1);
814269217Sian	atomic_add_32(&maps_total, 1);
815239268Sgonzo	dmat->map_count++;
816239268Sgonzo
817239268Sgonzo	CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
818239268Sgonzo	    __func__, dmat, dmat->flags, 0);
819239268Sgonzo	return (0);
820239268Sgonzo}
821239268Sgonzo
822239268Sgonzo/*
823289865Sian * Free a piece of memory that was allocated via bus_dmamem_alloc, along with
824289865Sian * its associated map.
825239268Sgonzo */
826239268Sgonzovoid
827239268Sgonzobus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
828239268Sgonzo{
829244469Scognet	struct busdma_bufzone *bufzone;
830244469Scognet	busdma_bufalloc_t ba;
831239268Sgonzo
832244469Scognet	if (map->flags & DMAMAP_COHERENT)
833244469Scognet		ba = coherent_allocator;
834244469Scognet	else
835244469Scognet		ba = standard_allocator;
836244469Scognet
837244469Scognet	bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
838244469Scognet
839244469Scognet	if (bufzone != NULL && dmat->alignment <= bufzone->size &&
840269207Sian	    !exclusion_bounce(dmat))
841244469Scognet		uma_zfree(bufzone->umazone, vaddr);
842244469Scognet	else
843254025Sjeff		kmem_free(kernel_arena, (vm_offset_t)vaddr, dmat->maxsize);
844244469Scognet
845239268Sgonzo	dmat->map_count--;
846269217Sian	if (map->flags & DMAMAP_COHERENT)
847269217Sian		atomic_subtract_32(&maps_coherent, 1);
848269217Sian	atomic_subtract_32(&maps_total, 1);
849269217Sian	atomic_subtract_32(&maps_dmamem, 1);
850289858Sian	free(map, M_BUSDMA);
851239268Sgonzo	CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat, dmat->flags);
852239268Sgonzo}
853239268Sgonzo
854246713Skibstatic void
855246713Skib_bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
856246713Skib    bus_size_t buflen, int flags)
857246713Skib{
858246713Skib	bus_addr_t curaddr;
859246713Skib	bus_size_t sgsize;
860246713Skib
861246713Skib	if (map->pagesneeded == 0) {
862246713Skib		CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
863246713Skib		    " map= %p, pagesneeded= %d",
864246713Skib		    dmat->lowaddr, dmat->boundary, dmat->alignment,
865246713Skib		    map, map->pagesneeded);
866246713Skib		/*
867246713Skib		 * Count the number of bounce pages
868246713Skib		 * needed in order to complete this transfer
869246713Skib		 */
870246713Skib		curaddr = buf;
871246713Skib		while (buflen != 0) {
872246713Skib			sgsize = MIN(buflen, dmat->maxsegsz);
873269211Sian			if (must_bounce(dmat, map, curaddr, sgsize) != 0) {
874289759Sjah				sgsize = MIN(sgsize,
875289759Sjah				    PAGE_SIZE - (curaddr & PAGE_MASK));
876246713Skib				map->pagesneeded++;
877246713Skib			}
878246713Skib			curaddr += sgsize;
879246713Skib			buflen -= sgsize;
880246713Skib		}
881246713Skib		CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
882246713Skib	}
883246713Skib}
884246713Skib
885246713Skibstatic void
886289759Sjah_bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap, bus_dmamap_t map,
887239268Sgonzo    void *buf, bus_size_t buflen, int flags)
888239268Sgonzo{
889239268Sgonzo	vm_offset_t vaddr;
890239268Sgonzo	vm_offset_t vendaddr;
891239268Sgonzo	bus_addr_t paddr;
892239268Sgonzo
893239268Sgonzo	if (map->pagesneeded == 0) {
894239268Sgonzo		CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
895239268Sgonzo		    " map= %p, pagesneeded= %d",
896239268Sgonzo		    dmat->lowaddr, dmat->boundary, dmat->alignment,
897239268Sgonzo		    map, map->pagesneeded);
898239268Sgonzo		/*
899239268Sgonzo		 * Count the number of bounce pages
900239268Sgonzo		 * needed in order to complete this transfer
901239268Sgonzo		 */
902239268Sgonzo		vaddr = (vm_offset_t)buf;
903239268Sgonzo		vendaddr = (vm_offset_t)buf + buflen;
904239268Sgonzo
905239268Sgonzo		while (vaddr < vendaddr) {
906289759Sjah			if (__predict_true(pmap == kernel_pmap))
907239268Sgonzo				paddr = pmap_kextract(vaddr);
908239268Sgonzo			else
909289759Sjah				paddr = pmap_extract(pmap, vaddr);
910269211Sian			if (must_bounce(dmat, map, paddr,
911283366Sandrew			    min(vendaddr - vaddr, (PAGE_SIZE - ((vm_offset_t)vaddr &
912269211Sian			    PAGE_MASK)))) != 0) {
913239268Sgonzo				map->pagesneeded++;
914239268Sgonzo			}
915239268Sgonzo			vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
916239268Sgonzo
917239268Sgonzo		}
918239268Sgonzo		CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
919239268Sgonzo	}
920246713Skib}
921239268Sgonzo
922246713Skibstatic int
923246713Skib_bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int flags)
924246713Skib{
925246713Skib
926239268Sgonzo	/* Reserve Necessary Bounce Pages */
927246713Skib	mtx_lock(&bounce_lock);
928246713Skib	if (flags & BUS_DMA_NOWAIT) {
929246713Skib		if (reserve_bounce_pages(dmat, map, 0) != 0) {
930246713Skib			map->pagesneeded = 0;
931246713Skib			mtx_unlock(&bounce_lock);
932246713Skib			return (ENOMEM);
933239268Sgonzo		}
934246713Skib	} else {
935246713Skib		if (reserve_bounce_pages(dmat, map, 1) != 0) {
936246713Skib			/* Queue us for resources */
937246713Skib			STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
938246713Skib			mtx_unlock(&bounce_lock);
939246713Skib			return (EINPROGRESS);
940246713Skib		}
941239268Sgonzo	}
942246713Skib	mtx_unlock(&bounce_lock);
943239268Sgonzo
944239268Sgonzo	return (0);
945239268Sgonzo}
946239268Sgonzo
947239268Sgonzo/*
948246713Skib * Add a single contiguous physical range to the segment list.
949246713Skib */
950246713Skibstatic int
951246713Skib_bus_dmamap_addseg(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t curaddr,
952289851Sian    bus_size_t sgsize, bus_dma_segment_t *segs, int *segp)
953246713Skib{
954246713Skib	bus_addr_t baddr, bmask;
955246713Skib	int seg;
956246713Skib
957246713Skib	/*
958246713Skib	 * Make sure we don't cross any boundaries.
959246713Skib	 */
960246713Skib	bmask = ~(dmat->boundary - 1);
961246713Skib	if (dmat->boundary > 0) {
962246713Skib		baddr = (curaddr + dmat->boundary) & bmask;
963246713Skib		if (sgsize > (baddr - curaddr))
964246713Skib			sgsize = (baddr - curaddr);
965246713Skib	}
966246713Skib
967246713Skib	/*
968246713Skib	 * Insert chunk into a segment, coalescing with
969246713Skib	 * previous segment if possible.
970246713Skib	 */
971246713Skib	seg = *segp;
972246713Skib	if (seg == -1) {
973246713Skib		seg = 0;
974246713Skib		segs[seg].ds_addr = curaddr;
975246713Skib		segs[seg].ds_len = sgsize;
976246713Skib	} else {
977246713Skib		if (curaddr == segs[seg].ds_addr + segs[seg].ds_len &&
978246713Skib		    (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
979246713Skib		    (dmat->boundary == 0 ||
980289851Sian		    (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
981246713Skib			segs[seg].ds_len += sgsize;
982246713Skib		else {
983246713Skib			if (++seg >= dmat->nsegments)
984246713Skib				return (0);
985246713Skib			segs[seg].ds_addr = curaddr;
986246713Skib			segs[seg].ds_len = sgsize;
987246713Skib		}
988246713Skib	}
989246713Skib	*segp = seg;
990246713Skib	return (sgsize);
991246713Skib}
992246713Skib
993246713Skib/*
994246713Skib * Utility function to load a physical buffer.  segp contains
995239268Sgonzo * the starting segment on entrace, and the ending segment on exit.
996239268Sgonzo */
997246713Skibint
998289851Sian_bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
999289851Sian    bus_size_t buflen, int flags, bus_dma_segment_t *segs, int *segp)
1000246713Skib{
1001246713Skib	bus_addr_t curaddr;
1002289759Sjah	bus_addr_t sl_end = 0;
1003246713Skib	bus_size_t sgsize;
1004289759Sjah	struct sync_list *sl;
1005246713Skib	int error;
1006246713Skib
1007246713Skib	if (segs == NULL)
1008269216Sian		segs = map->segments;
1009246713Skib
1010269321Sian	counter_u64_add(maploads_total, 1);
1011269321Sian	counter_u64_add(maploads_physmem, 1);
1012269217Sian
1013289759Sjah	if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1014246713Skib		_bus_dmamap_count_phys(dmat, map, buf, buflen, flags);
1015246713Skib		if (map->pagesneeded != 0) {
1016269321Sian			counter_u64_add(maploads_bounced, 1);
1017246713Skib			error = _bus_dmamap_reserve_pages(dmat, map, flags);
1018246713Skib			if (error)
1019246713Skib				return (error);
1020246713Skib		}
1021246713Skib	}
1022246713Skib
1023289759Sjah	sl = map->slist + map->sync_count - 1;
1024289759Sjah
1025246713Skib	while (buflen > 0) {
1026246713Skib		curaddr = buf;
1027246713Skib		sgsize = MIN(buflen, dmat->maxsegsz);
1028269211Sian		if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1029269211Sian		    sgsize)) {
1030289759Sjah			sgsize = MIN(sgsize, PAGE_SIZE - (curaddr & PAGE_MASK));
1031246713Skib			curaddr = add_bounce_page(dmat, map, 0, curaddr,
1032289865Sian			    sgsize);
1033289759Sjah		} else {
1034289759Sjah			if (map->sync_count > 0)
1035291018Smmel				sl_end = sl->paddr + sl->datacount;
1036289759Sjah
1037289759Sjah			if (map->sync_count == 0 || curaddr != sl_end) {
1038289759Sjah				if (++map->sync_count > dmat->nsegments)
1039289759Sjah					break;
1040289759Sjah				sl++;
1041289759Sjah				sl->vaddr = 0;
1042291018Smmel				sl->paddr = curaddr;
1043289759Sjah				sl->datacount = sgsize;
1044289759Sjah				sl->pages = PHYS_TO_VM_PAGE(curaddr);
1045291018Smmel				KASSERT(sl->pages != NULL,
1046291018Smmel				    ("%s: page at PA:0x%08lx is not in "
1047291018Smmel				    "vm_page_array", __func__, curaddr));
1048289759Sjah			} else
1049289759Sjah				sl->datacount += sgsize;
1050246713Skib		}
1051246713Skib		sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1052246713Skib		    segp);
1053246713Skib		if (sgsize == 0)
1054246713Skib			break;
1055246713Skib		buf += sgsize;
1056246713Skib		buflen -= sgsize;
1057246713Skib	}
1058246713Skib
1059246713Skib	/*
1060246713Skib	 * Did we fit?
1061246713Skib	 */
1062246713Skib	if (buflen != 0) {
1063246713Skib		_bus_dmamap_unload(dmat, map);
1064246713Skib		return (EFBIG); /* XXX better return value here? */
1065246713Skib	}
1066246713Skib	return (0);
1067246713Skib}
1068246713Skib
1069257228Skibint
1070257228Skib_bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map,
1071257228Skib    struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
1072257228Skib    bus_dma_segment_t *segs, int *segp)
1073257228Skib{
1074257228Skib
1075257228Skib	return (bus_dmamap_load_ma_triv(dmat, map, ma, tlen, ma_offs, flags,
1076257228Skib	    segs, segp));
1077257228Skib}
1078257228Skib
1079246713Skib/*
1080246713Skib * Utility function to load a linear buffer.  segp contains
1081289851Sian * the starting segment on entrance, and the ending segment on exit.
1082246713Skib */
1083246713Skibint
1084289851Sian_bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
1085289851Sian    bus_size_t buflen, pmap_t pmap, int flags, bus_dma_segment_t *segs,
1086289851Sian    int *segp)
1087239268Sgonzo{
1088239268Sgonzo	bus_size_t sgsize;
1089246713Skib	bus_addr_t curaddr;
1090289759Sjah	bus_addr_t sl_pend = 0;
1091289759Sjah	vm_offset_t kvaddr, vaddr, sl_vend = 0;
1092239268Sgonzo	struct sync_list *sl;
1093246713Skib	int error;
1094239268Sgonzo
1095269321Sian	counter_u64_add(maploads_total, 1);
1096269217Sian	if (map->flags & DMAMAP_COHERENT)
1097269321Sian		counter_u64_add(maploads_coherent, 1);
1098269217Sian	if (map->flags & DMAMAP_DMAMEM_ALLOC)
1099269321Sian		counter_u64_add(maploads_dmamem, 1);
1100269217Sian
1101246713Skib	if (segs == NULL)
1102269216Sian		segs = map->segments;
1103246713Skib
1104269217Sian	if (flags & BUS_DMA_LOAD_MBUF) {
1105269321Sian		counter_u64_add(maploads_mbuf, 1);
1106269212Sian		map->flags |= DMAMAP_MBUF;
1107269217Sian	}
1108269212Sian
1109269211Sian	if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1110289759Sjah		_bus_dmamap_count_pages(dmat, pmap, map, buf, buflen, flags);
1111246713Skib		if (map->pagesneeded != 0) {
1112269321Sian			counter_u64_add(maploads_bounced, 1);
1113246713Skib			error = _bus_dmamap_reserve_pages(dmat, map, flags);
1114246713Skib			if (error)
1115246713Skib				return (error);
1116246713Skib		}
1117239268Sgonzo	}
1118239268Sgonzo
1119289759Sjah	sl = map->slist + map->sync_count - 1;
1120239268Sgonzo	vaddr = (vm_offset_t)buf;
1121239268Sgonzo
1122246713Skib	while (buflen > 0) {
1123239268Sgonzo		/*
1124239268Sgonzo		 * Get the physical address for this segment.
1125239268Sgonzo		 */
1126289759Sjah		if (__predict_true(pmap == kernel_pmap)) {
1127239268Sgonzo			curaddr = pmap_kextract(vaddr);
1128289759Sjah			kvaddr = vaddr;
1129289759Sjah		} else {
1130289759Sjah			curaddr = pmap_extract(pmap, vaddr);
1131289759Sjah			kvaddr = 0;
1132289759Sjah		}
1133239268Sgonzo
1134239268Sgonzo		/*
1135239268Sgonzo		 * Compute the segment size, and adjust counts.
1136239268Sgonzo		 */
1137289759Sjah		sgsize = PAGE_SIZE - (curaddr & PAGE_MASK);
1138239268Sgonzo		if (sgsize > dmat->maxsegsz)
1139239268Sgonzo			sgsize = dmat->maxsegsz;
1140239268Sgonzo		if (buflen < sgsize)
1141239268Sgonzo			sgsize = buflen;
1142239268Sgonzo
1143269211Sian		if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1144269211Sian		    sgsize)) {
1145289759Sjah			curaddr = add_bounce_page(dmat, map, kvaddr, curaddr,
1146289865Sian			    sgsize);
1147239268Sgonzo		} else {
1148289759Sjah			if (map->sync_count > 0) {
1149291018Smmel				sl_pend = sl->paddr + sl->datacount;
1150289759Sjah				sl_vend = sl->vaddr + sl->datacount;
1151289759Sjah			}
1152289759Sjah
1153246713Skib			if (map->sync_count == 0 ||
1154289759Sjah			    (kvaddr != 0 && kvaddr != sl_vend) ||
1155289759Sjah			    (curaddr != sl_pend)) {
1156289759Sjah
1157246713Skib				if (++map->sync_count > dmat->nsegments)
1158246713Skib					goto cleanup;
1159246713Skib				sl++;
1160289759Sjah				sl->vaddr = kvaddr;
1161291018Smmel				sl->paddr = curaddr;
1162291018Smmel				if (kvaddr != 0) {
1163291018Smmel					sl->pages = NULL;
1164291018Smmel				} else {
1165291018Smmel					sl->pages = PHYS_TO_VM_PAGE(curaddr);
1166291018Smmel					KASSERT(sl->pages != NULL,
1167291018Smmel					    ("%s: page at PA:0x%08lx is not "
1168291018Smmel					    "in vm_page_array", __func__,
1169291018Smmel					    curaddr));
1170291018Smmel				}
1171246713Skib				sl->datacount = sgsize;
1172246713Skib			} else
1173246713Skib				sl->datacount += sgsize;
1174239268Sgonzo		}
1175246713Skib		sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1176289851Sian		    segp);
1177246713Skib		if (sgsize == 0)
1178246713Skib			break;
1179239268Sgonzo		vaddr += sgsize;
1180239268Sgonzo		buflen -= sgsize;
1181239268Sgonzo	}
1182239268Sgonzo
1183239268Sgonzocleanup:
1184239268Sgonzo	/*
1185239268Sgonzo	 * Did we fit?
1186239268Sgonzo	 */
1187239268Sgonzo	if (buflen != 0) {
1188239268Sgonzo		_bus_dmamap_unload(dmat, map);
1189246713Skib		return (EFBIG); /* XXX better return value here? */
1190239268Sgonzo	}
1191239268Sgonzo	return (0);
1192239268Sgonzo}
1193239268Sgonzo
1194246713Skibvoid
1195289851Sian__bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map, struct memdesc *mem,
1196289851Sian    bus_dmamap_callback_t *callback, void *callback_arg)
1197239268Sgonzo{
1198239268Sgonzo
1199246713Skib	map->mem = *mem;
1200246713Skib	map->dmat = dmat;
1201239268Sgonzo	map->callback = callback;
1202239268Sgonzo	map->callback_arg = callback_arg;
1203239268Sgonzo}
1204239268Sgonzo
1205246713Skibbus_dma_segment_t *
1206246713Skib_bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map,
1207289851Sian    bus_dma_segment_t *segs, int nsegs, int error)
1208239268Sgonzo{
1209239268Sgonzo
1210246713Skib	if (segs == NULL)
1211269216Sian		segs = map->segments;
1212246713Skib	return (segs);
1213239268Sgonzo}
1214239268Sgonzo
1215239268Sgonzo/*
1216239268Sgonzo * Release the mapping held by map.
1217239268Sgonzo */
1218239268Sgonzovoid
1219239268Sgonzo_bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1220239268Sgonzo{
1221239268Sgonzo	struct bounce_page *bpage;
1222239268Sgonzo	struct bounce_zone *bz;
1223239268Sgonzo
1224239268Sgonzo	if ((bz = dmat->bounce_zone) != NULL) {
1225239268Sgonzo		while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1226239268Sgonzo			STAILQ_REMOVE_HEAD(&map->bpages, links);
1227239268Sgonzo			free_bounce_page(dmat, bpage);
1228239268Sgonzo		}
1229239268Sgonzo
1230239268Sgonzo		bz = dmat->bounce_zone;
1231239268Sgonzo		bz->free_bpages += map->pagesreserved;
1232239268Sgonzo		bz->reserved_bpages -= map->pagesreserved;
1233239268Sgonzo		map->pagesreserved = 0;
1234239268Sgonzo		map->pagesneeded = 0;
1235239268Sgonzo	}
1236246713Skib	map->sync_count = 0;
1237269212Sian	map->flags &= ~DMAMAP_MBUF;
1238239268Sgonzo}
1239239268Sgonzo
1240289759Sjahstatic void
1241289759Sjahdma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size)
1242239268Sgonzo{
1243283366Sandrew	/*
1244289759Sjah	 * Write back any partial cachelines immediately before and
1245289759Sjah	 * after the DMA region.  We don't need to round the address
1246289759Sjah	 * down to the nearest cacheline or specify the exact size,
1247289759Sjah	 * as dcache_wb_poc() will do the rounding for us and works
1248289759Sjah	 * at cacheline granularity.
1249274545Sian	 */
1250289893Sian	if (va & BUSDMA_DCACHE_MASK)
1251289759Sjah		dcache_wb_poc(va, pa, 1);
1252289893Sian	if ((va + size) & BUSDMA_DCACHE_MASK)
1253289759Sjah		dcache_wb_poc(va + size, pa + size, 1);
1254239268Sgonzo
1255289887Sian	dcache_inv_poc_dma(va, pa, size);
1256289759Sjah}
1257239268Sgonzo
1258289759Sjahstatic void
1259289759Sjahdma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op)
1260289759Sjah{
1261289759Sjah	uint32_t len, offset;
1262289759Sjah	vm_page_t m;
1263289759Sjah	vm_paddr_t pa;
1264289759Sjah	vm_offset_t va, tempva;
1265289759Sjah	bus_size_t size;
1266239268Sgonzo
1267291018Smmel	offset = sl->paddr & PAGE_MASK;
1268289759Sjah	m = sl->pages;
1269289759Sjah	size = sl->datacount;
1270291018Smmel	pa = sl->paddr;
1271289759Sjah
1272289759Sjah	for ( ; size != 0; size -= len, pa += len, offset = 0, ++m) {
1273289759Sjah		tempva = 0;
1274289759Sjah		if (sl->vaddr == 0) {
1275289759Sjah			len = min(PAGE_SIZE - offset, size);
1276289759Sjah			tempva = pmap_quick_enter_page(m);
1277289759Sjah			va = tempva | offset;
1278291018Smmel			KASSERT(pa == (VM_PAGE_TO_PHYS(m) | offset),
1279291018Smmel			    ("unexpected vm_page_t phys: 0x%08x != 0x%08x",
1280291018Smmel			    VM_PAGE_TO_PHYS(m) | offset, pa));
1281289759Sjah		} else {
1282289759Sjah			len = sl->datacount;
1283289759Sjah			va = sl->vaddr;
1284289759Sjah		}
1285289759Sjah
1286289759Sjah		switch (op) {
1287289759Sjah		case BUS_DMASYNC_PREWRITE:
1288289759Sjah		case BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD:
1289289759Sjah			dcache_wb_poc(va, pa, len);
1290289759Sjah			break;
1291289759Sjah		case BUS_DMASYNC_PREREAD:
1292289759Sjah			/*
1293289759Sjah			 * An mbuf may start in the middle of a cacheline. There
1294289759Sjah			 * will be no cpu writes to the beginning of that line
1295289759Sjah			 * (which contains the mbuf header) while dma is in
1296289759Sjah			 * progress.  Handle that case by doing a writeback of
1297289759Sjah			 * just the first cacheline before invalidating the
1298289759Sjah			 * overall buffer.  Any mbuf in a chain may have this
1299289759Sjah			 * misalignment.  Buffers which are not mbufs bounce if
1300289759Sjah			 * they are not aligned to a cacheline.
1301289759Sjah			 */
1302289759Sjah			dma_preread_safe(va, pa, len);
1303289759Sjah			break;
1304289759Sjah		case BUS_DMASYNC_POSTREAD:
1305289759Sjah		case BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE:
1306289759Sjah			dcache_inv_poc(va, pa, len);
1307289759Sjah			break;
1308289759Sjah		default:
1309289759Sjah			panic("unsupported combination of sync operations: "
1310289759Sjah                              "0x%08x\n", op);
1311289759Sjah		}
1312289759Sjah
1313289759Sjah		if (tempva != 0)
1314289759Sjah			pmap_quick_remove_page(tempva);
1315239268Sgonzo	}
1316239268Sgonzo}
1317239268Sgonzo
1318239268Sgonzovoid
1319239268Sgonzo_bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1320239268Sgonzo{
1321239268Sgonzo	struct bounce_page *bpage;
1322246713Skib	struct sync_list *sl, *end;
1323289759Sjah	vm_offset_t datavaddr, tempvaddr;
1324289759Sjah
1325289759Sjah	if (op == BUS_DMASYNC_POSTWRITE)
1326289759Sjah		return;
1327289759Sjah
1328248655Sian	/*
1329248655Sian	 * If the buffer was from user space, it is possible that this is not
1330248655Sian	 * the same vm map, especially on a POST operation.  It's not clear that
1331274605Sian	 * dma on userland buffers can work at all right now.  To be safe, until
1332274605Sian	 * we're able to test direct userland dma, panic on a map mismatch.
1333248655Sian	 */
1334239268Sgonzo	if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1335274605Sian
1336239268Sgonzo		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1337239268Sgonzo		    "performing bounce", __func__, dmat, dmat->flags, op);
1338239268Sgonzo
1339274605Sian		/*
1340274605Sian		 * For PREWRITE do a writeback.  Clean the caches from the
1341274605Sian		 * innermost to the outermost levels.
1342274605Sian		 */
1343239268Sgonzo		if (op & BUS_DMASYNC_PREWRITE) {
1344239268Sgonzo			while (bpage != NULL) {
1345289759Sjah				tempvaddr = 0;
1346289759Sjah				datavaddr = bpage->datavaddr;
1347289759Sjah				if (datavaddr == 0) {
1348289759Sjah					tempvaddr = pmap_quick_enter_page(
1349289759Sjah					    bpage->datapage);
1350289759Sjah					datavaddr = tempvaddr | bpage->dataoffs;
1351289759Sjah				}
1352289759Sjah				bcopy((void *)datavaddr, (void *)bpage->vaddr,
1353274596Sian				    bpage->datacount);
1354289759Sjah				if (tempvaddr != 0)
1355289759Sjah					pmap_quick_remove_page(tempvaddr);
1356289759Sjah				dcache_wb_poc(bpage->vaddr, bpage->busaddr,
1357239268Sgonzo				    bpage->datacount);
1358239268Sgonzo				bpage = STAILQ_NEXT(bpage, links);
1359239268Sgonzo			}
1360239268Sgonzo			dmat->bounce_zone->total_bounced++;
1361239268Sgonzo		}
1362239268Sgonzo
1363274605Sian		/*
1364274605Sian		 * Do an invalidate for PREREAD unless a writeback was already
1365274605Sian		 * done above due to PREWRITE also being set.  The reason for a
1366274605Sian		 * PREREAD invalidate is to prevent dirty lines currently in the
1367274605Sian		 * cache from being evicted during the DMA.  If a writeback was
1368274605Sian		 * done due to PREWRITE also being set there will be no dirty
1369274605Sian		 * lines and the POSTREAD invalidate handles the rest. The
1370274605Sian		 * invalidate is done from the innermost to outermost level. If
1371274605Sian		 * L2 were done first, a dirty cacheline could be automatically
1372274605Sian		 * evicted from L1 before we invalidated it, re-dirtying the L2.
1373274605Sian		 */
1374274602Sian		if ((op & BUS_DMASYNC_PREREAD) && !(op & BUS_DMASYNC_PREWRITE)) {
1375261418Scognet			bpage = STAILQ_FIRST(&map->bpages);
1376261418Scognet			while (bpage != NULL) {
1377289887Sian				dcache_inv_poc_dma(bpage->vaddr, bpage->busaddr,
1378261418Scognet				    bpage->datacount);
1379261418Scognet				bpage = STAILQ_NEXT(bpage, links);
1380261418Scognet			}
1381261418Scognet		}
1382274605Sian
1383274605Sian		/*
1384274605Sian		 * Re-invalidate the caches on a POSTREAD, even though they were
1385274605Sian		 * already invalidated at PREREAD time.  Aggressive prefetching
1386274605Sian		 * due to accesses to other data near the dma buffer could have
1387274605Sian		 * brought buffer data into the caches which is now stale.  The
1388274605Sian		 * caches are invalidated from the outermost to innermost; the
1389274605Sian		 * prefetches could be happening right now, and if L1 were
1390274605Sian		 * invalidated first, stale L2 data could be prefetched into L1.
1391274605Sian		 */
1392239268Sgonzo		if (op & BUS_DMASYNC_POSTREAD) {
1393239268Sgonzo			while (bpage != NULL) {
1394289759Sjah				dcache_inv_poc(bpage->vaddr, bpage->busaddr,
1395286969Sian				    bpage->datacount);
1396289759Sjah				tempvaddr = 0;
1397289759Sjah				datavaddr = bpage->datavaddr;
1398289759Sjah				if (datavaddr == 0) {
1399289759Sjah					tempvaddr = pmap_quick_enter_page(
1400289759Sjah					    bpage->datapage);
1401289759Sjah					datavaddr = tempvaddr | bpage->dataoffs;
1402289759Sjah				}
1403289759Sjah				bcopy((void *)bpage->vaddr, (void *)datavaddr,
1404286969Sian				    bpage->datacount);
1405289759Sjah				if (tempvaddr != 0)
1406289759Sjah					pmap_quick_remove_page(tempvaddr);
1407239268Sgonzo				bpage = STAILQ_NEXT(bpage, links);
1408239268Sgonzo			}
1409239268Sgonzo			dmat->bounce_zone->total_bounced++;
1410239268Sgonzo		}
1411239268Sgonzo	}
1412274538Sian
1413274538Sian	/*
1414274538Sian	 * For COHERENT memory no cache maintenance is necessary, but ensure all
1415274596Sian	 * writes have reached memory for the PREWRITE case.  No action is
1416274596Sian	 * needed for a PREREAD without PREWRITE also set, because that would
1417274596Sian	 * imply that the cpu had written to the COHERENT buffer and expected
1418274596Sian	 * the dma device to see that change, and by definition a PREWRITE sync
1419274596Sian	 * is required to make that happen.
1420274538Sian	 */
1421274538Sian	if (map->flags & DMAMAP_COHERENT) {
1422274538Sian		if (op & BUS_DMASYNC_PREWRITE) {
1423274596Sian			dsb();
1424274596Sian			cpu_l2cache_drain_writebuf();
1425274538Sian		}
1426244469Scognet		return;
1427274538Sian	}
1428239268Sgonzo
1429274605Sian	/*
1430274605Sian	 * Cache maintenance for normal (non-COHERENT non-bounce) buffers.  All
1431274605Sian	 * the comments about the sequences for flushing cache levels in the
1432274605Sian	 * bounce buffer code above apply here as well.  In particular, the fact
1433274605Sian	 * that the sequence is inner-to-outer for PREREAD invalidation and
1434274605Sian	 * outer-to-inner for POSTREAD invalidation is not a mistake.
1435274605Sian	 */
1436246713Skib	if (map->sync_count != 0) {
1437246713Skib		sl = &map->slist[0];
1438246713Skib		end = &map->slist[map->sync_count];
1439239268Sgonzo		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1440239268Sgonzo		    "performing sync", __func__, dmat, dmat->flags, op);
1441239268Sgonzo
1442289759Sjah		for ( ; sl != end; ++sl)
1443289759Sjah			dma_dcache_sync(sl, op);
1444239268Sgonzo	}
1445239268Sgonzo}
1446239268Sgonzo
1447239268Sgonzostatic void
1448239268Sgonzoinit_bounce_pages(void *dummy __unused)
1449239268Sgonzo{
1450239268Sgonzo
1451239268Sgonzo	total_bpages = 0;
1452239268Sgonzo	STAILQ_INIT(&bounce_zone_list);
1453239268Sgonzo	STAILQ_INIT(&bounce_map_waitinglist);
1454239268Sgonzo	STAILQ_INIT(&bounce_map_callbacklist);
1455239268Sgonzo	mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
1456239268Sgonzo}
1457239268SgonzoSYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
1458239268Sgonzo
1459239268Sgonzostatic struct sysctl_ctx_list *
1460239268Sgonzobusdma_sysctl_tree(struct bounce_zone *bz)
1461239268Sgonzo{
1462274545Sian
1463239268Sgonzo	return (&bz->sysctl_tree);
1464239268Sgonzo}
1465239268Sgonzo
1466239268Sgonzostatic struct sysctl_oid *
1467239268Sgonzobusdma_sysctl_tree_top(struct bounce_zone *bz)
1468239268Sgonzo{
1469274545Sian
1470239268Sgonzo	return (bz->sysctl_tree_top);
1471239268Sgonzo}
1472239268Sgonzo
1473239268Sgonzostatic int
1474239268Sgonzoalloc_bounce_zone(bus_dma_tag_t dmat)
1475239268Sgonzo{
1476239268Sgonzo	struct bounce_zone *bz;
1477239268Sgonzo
1478239268Sgonzo	/* Check to see if we already have a suitable zone */
1479239268Sgonzo	STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1480269209Sian		if ((dmat->alignment <= bz->alignment) &&
1481269209Sian		    (dmat->lowaddr >= bz->lowaddr)) {
1482239268Sgonzo			dmat->bounce_zone = bz;
1483239268Sgonzo			return (0);
1484239268Sgonzo		}
1485239268Sgonzo	}
1486239268Sgonzo
1487289858Sian	if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_BUSDMA,
1488239268Sgonzo	    M_NOWAIT | M_ZERO)) == NULL)
1489239268Sgonzo		return (ENOMEM);
1490239268Sgonzo
1491239268Sgonzo	STAILQ_INIT(&bz->bounce_page_list);
1492239268Sgonzo	bz->free_bpages = 0;
1493239268Sgonzo	bz->reserved_bpages = 0;
1494239268Sgonzo	bz->active_bpages = 0;
1495239268Sgonzo	bz->lowaddr = dmat->lowaddr;
1496239268Sgonzo	bz->alignment = MAX(dmat->alignment, PAGE_SIZE);
1497239268Sgonzo	bz->map_count = 0;
1498239268Sgonzo	snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1499239268Sgonzo	busdma_zonecount++;
1500239268Sgonzo	snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1501239268Sgonzo	STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1502239268Sgonzo	dmat->bounce_zone = bz;
1503239268Sgonzo
1504239268Sgonzo	sysctl_ctx_init(&bz->sysctl_tree);
1505239268Sgonzo	bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
1506239268Sgonzo	    SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1507239268Sgonzo	    CTLFLAG_RD, 0, "");
1508239268Sgonzo	if (bz->sysctl_tree_top == NULL) {
1509239268Sgonzo		sysctl_ctx_free(&bz->sysctl_tree);
1510239268Sgonzo		return (0);	/* XXX error code? */
1511239268Sgonzo	}
1512239268Sgonzo
1513239268Sgonzo	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1514239268Sgonzo	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1515239268Sgonzo	    "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1516239268Sgonzo	    "Total bounce pages");
1517239268Sgonzo	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1518239268Sgonzo	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1519239268Sgonzo	    "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1520239268Sgonzo	    "Free bounce pages");
1521239268Sgonzo	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1522239268Sgonzo	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1523239268Sgonzo	    "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1524239268Sgonzo	    "Reserved bounce pages");
1525239268Sgonzo	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1526239268Sgonzo	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1527239268Sgonzo	    "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1528239268Sgonzo	    "Active bounce pages");
1529239268Sgonzo	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1530239268Sgonzo	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1531239268Sgonzo	    "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1532269217Sian	    "Total bounce requests (pages bounced)");
1533239268Sgonzo	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1534239268Sgonzo	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1535239268Sgonzo	    "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1536239268Sgonzo	    "Total bounce requests that were deferred");
1537239268Sgonzo	SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1538239268Sgonzo	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1539239268Sgonzo	    "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1540273377Shselasky	SYSCTL_ADD_ULONG(busdma_sysctl_tree(bz),
1541239268Sgonzo	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1542273377Shselasky	    "alignment", CTLFLAG_RD, &bz->alignment, "");
1543239268Sgonzo
1544239268Sgonzo	return (0);
1545239268Sgonzo}
1546239268Sgonzo
1547239268Sgonzostatic int
1548239268Sgonzoalloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1549239268Sgonzo{
1550239268Sgonzo	struct bounce_zone *bz;
1551239268Sgonzo	int count;
1552239268Sgonzo
1553239268Sgonzo	bz = dmat->bounce_zone;
1554239268Sgonzo	count = 0;
1555239268Sgonzo	while (numpages > 0) {
1556239268Sgonzo		struct bounce_page *bpage;
1557239268Sgonzo
1558289858Sian		bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_BUSDMA,
1559269209Sian		    M_NOWAIT | M_ZERO);
1560239268Sgonzo
1561239268Sgonzo		if (bpage == NULL)
1562239268Sgonzo			break;
1563289858Sian		bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_BOUNCE,
1564269209Sian		    M_NOWAIT, 0ul, bz->lowaddr, PAGE_SIZE, 0);
1565239268Sgonzo		if (bpage->vaddr == 0) {
1566289858Sian			free(bpage, M_BUSDMA);
1567239268Sgonzo			break;
1568239268Sgonzo		}
1569239268Sgonzo		bpage->busaddr = pmap_kextract(bpage->vaddr);
1570239268Sgonzo		mtx_lock(&bounce_lock);
1571239268Sgonzo		STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1572239268Sgonzo		total_bpages++;
1573239268Sgonzo		bz->total_bpages++;
1574239268Sgonzo		bz->free_bpages++;
1575239268Sgonzo		mtx_unlock(&bounce_lock);
1576239268Sgonzo		count++;
1577239268Sgonzo		numpages--;
1578239268Sgonzo	}
1579239268Sgonzo	return (count);
1580239268Sgonzo}
1581239268Sgonzo
1582239268Sgonzostatic int
1583239268Sgonzoreserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1584239268Sgonzo{
1585239268Sgonzo	struct bounce_zone *bz;
1586239268Sgonzo	int pages;
1587239268Sgonzo
1588239268Sgonzo	mtx_assert(&bounce_lock, MA_OWNED);
1589239268Sgonzo	bz = dmat->bounce_zone;
1590239268Sgonzo	pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1591239268Sgonzo	if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1592239268Sgonzo		return (map->pagesneeded - (map->pagesreserved + pages));
1593239268Sgonzo	bz->free_bpages -= pages;
1594239268Sgonzo	bz->reserved_bpages += pages;
1595239268Sgonzo	map->pagesreserved += pages;
1596239268Sgonzo	pages = map->pagesneeded - map->pagesreserved;
1597239268Sgonzo
1598239268Sgonzo	return (pages);
1599239268Sgonzo}
1600239268Sgonzo
1601239268Sgonzostatic bus_addr_t
1602239268Sgonzoadd_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1603289851Sian    bus_addr_t addr, bus_size_t size)
1604239268Sgonzo{
1605239268Sgonzo	struct bounce_zone *bz;
1606239268Sgonzo	struct bounce_page *bpage;
1607239268Sgonzo
1608239268Sgonzo	KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1609289851Sian	KASSERT(map != NULL, ("add_bounce_page: bad map %p", map));
1610239268Sgonzo
1611239268Sgonzo	bz = dmat->bounce_zone;
1612239268Sgonzo	if (map->pagesneeded == 0)
1613239268Sgonzo		panic("add_bounce_page: map doesn't need any pages");
1614239268Sgonzo	map->pagesneeded--;
1615239268Sgonzo
1616239268Sgonzo	if (map->pagesreserved == 0)
1617239268Sgonzo		panic("add_bounce_page: map doesn't need any pages");
1618239268Sgonzo	map->pagesreserved--;
1619239268Sgonzo
1620239268Sgonzo	mtx_lock(&bounce_lock);
1621239268Sgonzo	bpage = STAILQ_FIRST(&bz->bounce_page_list);
1622239268Sgonzo	if (bpage == NULL)
1623239268Sgonzo		panic("add_bounce_page: free page list is empty");
1624239268Sgonzo
1625239268Sgonzo	STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1626239268Sgonzo	bz->reserved_bpages--;
1627239268Sgonzo	bz->active_bpages++;
1628239268Sgonzo	mtx_unlock(&bounce_lock);
1629239268Sgonzo
1630239268Sgonzo	if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1631239268Sgonzo		/* Page offset needs to be preserved. */
1632282120Shselasky		bpage->vaddr |= addr & PAGE_MASK;
1633282120Shselasky		bpage->busaddr |= addr & PAGE_MASK;
1634239268Sgonzo	}
1635239268Sgonzo	bpage->datavaddr = vaddr;
1636289759Sjah	bpage->datapage = PHYS_TO_VM_PAGE(addr);
1637289759Sjah	bpage->dataoffs = addr & PAGE_MASK;
1638239268Sgonzo	bpage->datacount = size;
1639239268Sgonzo	STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1640239268Sgonzo	return (bpage->busaddr);
1641239268Sgonzo}
1642239268Sgonzo
1643239268Sgonzostatic void
1644239268Sgonzofree_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1645239268Sgonzo{
1646239268Sgonzo	struct bus_dmamap *map;
1647239268Sgonzo	struct bounce_zone *bz;
1648239268Sgonzo
1649239268Sgonzo	bz = dmat->bounce_zone;
1650239268Sgonzo	bpage->datavaddr = 0;
1651239268Sgonzo	bpage->datacount = 0;
1652239268Sgonzo	if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1653239268Sgonzo		/*
1654239268Sgonzo		 * Reset the bounce page to start at offset 0.  Other uses
1655239268Sgonzo		 * of this bounce page may need to store a full page of
1656239268Sgonzo		 * data and/or assume it starts on a page boundary.
1657239268Sgonzo		 */
1658239268Sgonzo		bpage->vaddr &= ~PAGE_MASK;
1659239268Sgonzo		bpage->busaddr &= ~PAGE_MASK;
1660239268Sgonzo	}
1661239268Sgonzo
1662239268Sgonzo	mtx_lock(&bounce_lock);
1663239268Sgonzo	STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1664239268Sgonzo	bz->free_bpages++;
1665239268Sgonzo	bz->active_bpages--;
1666239268Sgonzo	if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1667239268Sgonzo		if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1668239268Sgonzo			STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1669239268Sgonzo			STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1670269209Sian			    map, links);
1671239268Sgonzo			busdma_swi_pending = 1;
1672239268Sgonzo			bz->total_deferred++;
1673239268Sgonzo			swi_sched(vm_ih, 0);
1674239268Sgonzo		}
1675239268Sgonzo	}
1676239268Sgonzo	mtx_unlock(&bounce_lock);
1677239268Sgonzo}
1678239268Sgonzo
1679239268Sgonzovoid
1680239268Sgonzobusdma_swi(void)
1681239268Sgonzo{
1682239268Sgonzo	bus_dma_tag_t dmat;
1683239268Sgonzo	struct bus_dmamap *map;
1684239268Sgonzo
1685239268Sgonzo	mtx_lock(&bounce_lock);
1686239268Sgonzo	while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1687239268Sgonzo		STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1688239268Sgonzo		mtx_unlock(&bounce_lock);
1689239268Sgonzo		dmat = map->dmat;
1690269209Sian		dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_LOCK);
1691246713Skib		bus_dmamap_load_mem(map->dmat, map, &map->mem, map->callback,
1692269209Sian		    map->callback_arg, BUS_DMA_WAITOK);
1693269209Sian		dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_UNLOCK);
1694239268Sgonzo		mtx_lock(&bounce_lock);
1695239268Sgonzo	}
1696239268Sgonzo	mtx_unlock(&bounce_lock);
1697239268Sgonzo}
1698