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