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