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