busdma_machdep-v4.c revision 289862
1/*-
2 * Copyright (c) 2012 Ian Lepore
3 * Copyright (c) 2004 Olivier Houchard
4 * Copyright (c) 2002 Peter Grehan
5 * Copyright (c) 1997, 1998 Justin T. Gibbs.
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions, and the following disclaimer,
13 *    without modification, immediately at the beginning of the file.
14 * 2. The name of the author may not be used to endorse or promote products
15 *    derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
21 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 *   From i386/busdma_machdep.c,v 1.26 2002/04/19 22:58:09 alfred
30 */
31
32#include <sys/cdefs.h>
33__FBSDID("$FreeBSD: head/sys/arm/arm/busdma_machdep.c 289862 2015-10-24 02:18:14Z ian $");
34
35/*
36 * ARM bus dma support routines.
37 *
38 * XXX Things to investigate / fix some day...
39 *  - What is the earliest that this API can be called?  Could there be any
40 *    fallout from changing the SYSINIT() order from SI_SUB_VM to SI_SUB_KMEM?
41 *  - The manpage mentions the BUS_DMA_NOWAIT flag only in the context of the
42 *    bus_dmamap_load() function.  This code has historically (and still does)
43 *    honor it in bus_dmamem_alloc().  If we got rid of that we could lose some
44 *    error checking because some resource management calls would become WAITOK
45 *    and thus "cannot fail."
46 *  - The decisions made by _bus_dma_can_bounce() should be made once, at tag
47 *    creation time, and the result stored in the tag.
48 *  - It should be possible to take some shortcuts when mapping a buffer we know
49 *    came from the uma(9) allocators based on what we know about such buffers
50 *    (aligned, contiguous, etc).
51 *  - The allocation of bounce pages could probably be cleaned up, then we could
52 *    retire arm_remap_nocache().
53 */
54
55#define _ARM32_BUS_DMA_PRIVATE
56#include <sys/param.h>
57#include <sys/systm.h>
58#include <sys/malloc.h>
59#include <sys/bus.h>
60#include <sys/busdma_bufalloc.h>
61#include <sys/interrupt.h>
62#include <sys/lock.h>
63#include <sys/proc.h>
64#include <sys/memdesc.h>
65#include <sys/mutex.h>
66#include <sys/ktr.h>
67#include <sys/kernel.h>
68#include <sys/sysctl.h>
69#include <sys/uio.h>
70
71#include <vm/uma.h>
72#include <vm/vm.h>
73#include <vm/vm_extern.h>
74#include <vm/vm_kern.h>
75#include <vm/vm_page.h>
76#include <vm/vm_map.h>
77
78#include <machine/atomic.h>
79#include <machine/bus.h>
80#include <machine/cpufunc.h>
81#include <machine/md_var.h>
82
83#define	MAX_BPAGES		64
84#define	MAX_DMA_SEGMENTS	4096
85#define	BUS_DMA_COULD_BOUNCE	BUS_DMA_BUS3
86#define	BUS_DMA_MIN_ALLOC_COMP	BUS_DMA_BUS4
87
88struct bounce_zone;
89
90struct bus_dma_tag {
91	bus_dma_tag_t		parent;
92	bus_size_t		alignment;
93	bus_addr_t		boundary;
94	bus_addr_t		lowaddr;
95	bus_addr_t		highaddr;
96	bus_dma_filter_t	*filter;
97	void			*filterarg;
98	bus_size_t		maxsize;
99	u_int			nsegments;
100	bus_size_t		maxsegsz;
101	int			flags;
102	int			ref_count;
103	int			map_count;
104	bus_dma_lock_t		*lockfunc;
105	void			*lockfuncarg;
106	struct bounce_zone	*bounce_zone;
107	/*
108	 * DMA range for this tag.  If the page doesn't fall within
109	 * one of these ranges, an error is returned.  The caller
110	 * may then decide what to do with the transfer.  If the
111	 * range pointer is NULL, it is ignored.
112	 */
113	struct arm32_dma_range	*ranges;
114	int			_nranges;
115};
116
117struct bounce_page {
118	vm_offset_t	vaddr;		/* kva of bounce buffer */
119	bus_addr_t	busaddr;	/* Physical address */
120	vm_offset_t	datavaddr;	/* kva of client data */
121	vm_page_t	datapage;	/* physical page of client data */
122	vm_offset_t	dataoffs;	/* page offset of client data */
123	bus_size_t	datacount;	/* client data count */
124	STAILQ_ENTRY(bounce_page) links;
125};
126
127struct sync_list {
128	vm_offset_t	vaddr;		/* kva of client data */
129	vm_page_t	pages;		/* starting page of client data */
130	vm_offset_t	dataoffs;	/* page offset of client data */
131	bus_size_t	datacount;	/* client data count */
132};
133
134int busdma_swi_pending;
135
136struct bounce_zone {
137	STAILQ_ENTRY(bounce_zone) links;
138	STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
139	int		total_bpages;
140	int		free_bpages;
141	int		reserved_bpages;
142	int		active_bpages;
143	int		total_bounced;
144	int		total_deferred;
145	int		map_count;
146	bus_size_t	alignment;
147	bus_addr_t	lowaddr;
148	char		zoneid[8];
149	char		lowaddrid[20];
150	struct sysctl_ctx_list sysctl_tree;
151	struct sysctl_oid *sysctl_tree_top;
152};
153
154static struct mtx bounce_lock;
155static int total_bpages;
156static int busdma_zonecount;
157static STAILQ_HEAD(, bounce_zone) bounce_zone_list;
158
159static SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
160SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bpages, 0,
161	   "Total bounce pages");
162
163struct bus_dmamap {
164	struct bp_list		bpages;
165	int			pagesneeded;
166	int			pagesreserved;
167	bus_dma_tag_t		dmat;
168	struct memdesc		mem;
169	bus_dmamap_callback_t	*callback;
170	void			*callback_arg;
171	int			flags;
172#define	DMAMAP_COHERENT		(1 << 0)
173#define	DMAMAP_DMAMEM_ALLOC	(1 << 1)
174#define	DMAMAP_MBUF		(1 << 2)
175#define	DMAMAP_CACHE_ALIGNED	(1 << 3)
176	STAILQ_ENTRY(bus_dmamap) links;
177	bus_dma_segment_t	*segments;
178	int			sync_count;
179	struct sync_list	slist[];
180};
181
182static STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
183static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist;
184
185static void init_bounce_pages(void *dummy);
186static int alloc_bounce_zone(bus_dma_tag_t dmat);
187static int alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages);
188static int reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
189    int commit);
190static bus_addr_t add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map,
191    vm_offset_t vaddr, bus_addr_t addr, bus_size_t size);
192static void free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage);
193static void bus_dmamap_sync_sl(struct sync_list *sl, bus_dmasync_op_t op,
194    int bufaligned);
195
196/* Default tag, as most drivers provide no parent tag. */
197bus_dma_tag_t arm_root_dma_tag;
198
199/*
200 * ----------------------------------------------------------------------------
201 * Begin block of code useful to transplant to other implementations.
202 */
203
204static busdma_bufalloc_t coherent_allocator;	/* Cache of coherent buffers */
205static busdma_bufalloc_t standard_allocator;	/* Cache of standard buffers */
206
207MALLOC_DEFINE(M_BUSDMA, "busdma", "busdma metadata");
208MALLOC_DEFINE(M_BOUNCE, "bounce", "busdma bounce pages");
209
210static void
211busdma_init(void *dummy)
212{
213
214
215	/* Create a cache of buffers in standard (cacheable) memory. */
216	standard_allocator = busdma_bufalloc_create("buffer",
217	    arm_dcache_align,	/* minimum_alignment */
218	    NULL,		/* uma_alloc func */
219	    NULL,		/* uma_free func */
220	    0);			/* uma_zcreate_flags */
221
222	/*
223	 * Create a cache of buffers in uncacheable memory, to implement the
224	 * BUS_DMA_COHERENT (and potentially BUS_DMA_NOCACHE) flag.
225	 */
226	coherent_allocator = busdma_bufalloc_create("coherent",
227	    arm_dcache_align,	/* minimum_alignment */
228	    busdma_bufalloc_alloc_uncacheable,
229	    busdma_bufalloc_free_uncacheable,
230	    0);			/* uma_zcreate_flags */
231}
232
233/*
234 * This init historically used SI_SUB_VM, but now the init code requires
235 * malloc(9) using M_BUSDMA memory and the pcpu zones for counter(9), which get
236 * set up by SI_SUB_KMEM and SI_ORDER_LAST, so we'll go right after that by
237 * using SI_SUB_KMEM+1.
238 */
239SYSINIT(busdma, SI_SUB_KMEM+1, SI_ORDER_FIRST, busdma_init, NULL);
240
241/*
242 * End block of code useful to transplant to other implementations.
243 * ----------------------------------------------------------------------------
244 */
245
246/*
247 * Return true if a match is made.
248 *
249 * To find a match walk the chain of bus_dma_tag_t's looking for 'paddr'.
250 *
251 * If paddr is within the bounds of the dma tag then call the filter callback
252 * to check for a match, if there is no filter callback then assume a match.
253 */
254static int
255run_filter(bus_dma_tag_t dmat, bus_addr_t paddr)
256{
257	int retval;
258
259	retval = 0;
260
261	do {
262		if (((paddr > dmat->lowaddr && paddr <= dmat->highaddr)
263		 || ((paddr & (dmat->alignment - 1)) != 0))
264		 && (dmat->filter == NULL
265		  || (*dmat->filter)(dmat->filterarg, paddr) != 0))
266			retval = 1;
267
268		dmat = dmat->parent;
269	} while (retval == 0 && dmat != NULL);
270	return (retval);
271}
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 __inline int
286_bus_dma_can_bounce(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] &&
296		    highaddr > phys_avail[i]))
297			return (1);
298	}
299	return (0);
300}
301
302static __inline struct arm32_dma_range *
303_bus_dma_inrange(struct arm32_dma_range *ranges, int nranges,
304    bus_addr_t curaddr)
305{
306	struct arm32_dma_range *dr;
307	int i;
308
309	for (i = 0, dr = ranges; i < nranges; i++, dr++) {
310		if (curaddr >= dr->dr_sysbase &&
311		    round_page(curaddr) <= (dr->dr_sysbase + dr->dr_len))
312			return (dr);
313	}
314
315	return (NULL);
316}
317
318/*
319 * Convenience function for manipulating driver locks from busdma (during
320 * busdma_swi, for example).  Drivers that don't provide their own locks
321 * should specify &Giant to dmat->lockfuncarg.  Drivers that use their own
322 * non-mutex locking scheme don't have to use this at all.
323 */
324void
325busdma_lock_mutex(void *arg, bus_dma_lock_op_t op)
326{
327	struct mtx *dmtx;
328
329	dmtx = (struct mtx *)arg;
330	switch (op) {
331	case BUS_DMA_LOCK:
332		mtx_lock(dmtx);
333		break;
334	case BUS_DMA_UNLOCK:
335		mtx_unlock(dmtx);
336		break;
337	default:
338		panic("Unknown operation 0x%x for busdma_lock_mutex!", op);
339	}
340}
341
342/*
343 * dflt_lock should never get called.  It gets put into the dma tag when
344 * lockfunc == NULL, which is only valid if the maps that are associated
345 * with the tag are meant to never be defered.
346 * XXX Should have a way to identify which driver is responsible here.
347 */
348static void
349dflt_lock(void *arg, bus_dma_lock_op_t op)
350{
351#ifdef INVARIANTS
352	panic("driver error: busdma dflt_lock called");
353#else
354	printf("DRIVER_ERROR: busdma dflt_lock called\n");
355#endif
356}
357
358/*
359 * Allocate a device specific dma_tag.
360 */
361int
362bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
363    bus_addr_t boundary, bus_addr_t lowaddr, bus_addr_t highaddr,
364    bus_dma_filter_t *filter, void *filterarg, bus_size_t maxsize,
365    int nsegments, bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
366    void *lockfuncarg, bus_dma_tag_t *dmat)
367{
368	bus_dma_tag_t newtag;
369	int error = 0;
370	/* Return a NULL tag on failure */
371	*dmat = NULL;
372	if (!parent)
373		parent = arm_root_dma_tag;
374
375	newtag = (bus_dma_tag_t)malloc(sizeof(*newtag), M_BUSDMA, M_NOWAIT);
376	if (newtag == NULL) {
377		CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
378		    __func__, newtag, 0, error);
379		return (ENOMEM);
380	}
381
382	newtag->parent = parent;
383	newtag->alignment = alignment ? alignment : 1;
384	newtag->boundary = boundary;
385	newtag->lowaddr = trunc_page((vm_offset_t)lowaddr) + (PAGE_SIZE - 1);
386	newtag->highaddr = trunc_page((vm_offset_t)highaddr) + (PAGE_SIZE - 1);
387	newtag->filter = filter;
388	newtag->filterarg = filterarg;
389	newtag->maxsize = maxsize;
390	newtag->nsegments = nsegments;
391	newtag->maxsegsz = maxsegsz;
392	newtag->flags = flags;
393	newtag->ref_count = 1; /* Count ourself */
394	newtag->map_count = 0;
395	newtag->ranges = bus_dma_get_range();
396	newtag->_nranges = bus_dma_get_range_nb();
397	if (lockfunc != NULL) {
398		newtag->lockfunc = lockfunc;
399		newtag->lockfuncarg = lockfuncarg;
400	} else {
401		newtag->lockfunc = dflt_lock;
402		newtag->lockfuncarg = NULL;
403	}
404
405	/* Take into account any restrictions imposed by our parent tag */
406	if (parent != NULL) {
407		newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
408		newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
409		if (newtag->boundary == 0)
410			newtag->boundary = parent->boundary;
411		else if (parent->boundary != 0)
412			newtag->boundary = MIN(parent->boundary,
413					       newtag->boundary);
414		if ((newtag->filter != NULL) ||
415		    ((parent->flags & BUS_DMA_COULD_BOUNCE) != 0))
416			newtag->flags |= BUS_DMA_COULD_BOUNCE;
417		if (newtag->filter == NULL) {
418			/*
419			 * Short circuit looking at our parent directly
420			 * since we have encapsulated all of its information
421			 */
422			newtag->filter = parent->filter;
423			newtag->filterarg = parent->filterarg;
424			newtag->parent = parent->parent;
425		}
426		if (newtag->parent != NULL)
427			atomic_add_int(&parent->ref_count, 1);
428	}
429	if (_bus_dma_can_bounce(newtag->lowaddr, newtag->highaddr)
430	 || newtag->alignment > 1)
431		newtag->flags |= BUS_DMA_COULD_BOUNCE;
432
433	if (((newtag->flags & BUS_DMA_COULD_BOUNCE) != 0) &&
434	    (flags & BUS_DMA_ALLOCNOW) != 0) {
435		struct bounce_zone *bz;
436
437		/* Must bounce */
438
439		if ((error = alloc_bounce_zone(newtag)) != 0) {
440			free(newtag, M_BUSDMA);
441			return (error);
442		}
443		bz = newtag->bounce_zone;
444
445		if (ptoa(bz->total_bpages) < maxsize) {
446			int pages;
447
448			pages = atop(maxsize) - bz->total_bpages;
449
450			/* Add pages to our bounce pool */
451			if (alloc_bounce_pages(newtag, pages) < pages)
452				error = ENOMEM;
453		}
454		/* Performed initial allocation */
455		newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
456	} else
457		newtag->bounce_zone = NULL;
458	if (error != 0)
459		free(newtag, M_BUSDMA);
460	else
461		*dmat = newtag;
462	CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
463	    __func__, newtag, (newtag != NULL ? newtag->flags : 0), error);
464
465	return (error);
466}
467
468int
469bus_dma_tag_destroy(bus_dma_tag_t dmat)
470{
471#ifdef KTR
472	bus_dma_tag_t dmat_copy = dmat;
473#endif
474
475	if (dmat != NULL) {
476
477		if (dmat->map_count != 0)
478			return (EBUSY);
479
480		while (dmat != NULL) {
481			bus_dma_tag_t parent;
482
483			parent = dmat->parent;
484			atomic_subtract_int(&dmat->ref_count, 1);
485			if (dmat->ref_count == 0) {
486				free(dmat, M_BUSDMA);
487				/*
488				 * Last reference count, so
489				 * release our reference
490				 * count on our parent.
491				 */
492				dmat = parent;
493			} else
494				dmat = NULL;
495		}
496	}
497	CTR2(KTR_BUSDMA, "%s tag %p", __func__, dmat_copy);
498
499	return (0);
500}
501
502static bus_dmamap_t
503allocate_map(bus_dma_tag_t dmat, int mflags)
504{
505	int mapsize, segsize;
506	bus_dmamap_t map;
507
508	/*
509	 * Allocate the map.  The map structure ends with an embedded
510	 * variable-sized array of sync_list structures.  Following that
511	 * we allocate enough extra space to hold the array of bus_dma_segments.
512	 */
513	KASSERT(dmat->nsegments <= MAX_DMA_SEGMENTS,
514	   ("cannot allocate %u dma segments (max is %u)",
515	    dmat->nsegments, MAX_DMA_SEGMENTS));
516	segsize = sizeof(struct bus_dma_segment) * dmat->nsegments;
517	mapsize = sizeof(*map) + sizeof(struct sync_list) * dmat->nsegments;
518	map = malloc(mapsize + segsize, M_BUSDMA, mflags | M_ZERO);
519	if (map == NULL) {
520		CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
521		return (NULL);
522	}
523	map->segments = (bus_dma_segment_t *)((uintptr_t)map + mapsize);
524	return (map);
525}
526
527/*
528 * Allocate a handle for mapping from kva/uva/physical
529 * address space into bus device space.
530 */
531int
532bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
533{
534	bus_dmamap_t map;
535	int error = 0;
536
537	*mapp = map = allocate_map(dmat, M_NOWAIT);
538	if (map == NULL) {
539		CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
540		return (ENOMEM);
541	}
542
543	/*
544	 * Bouncing might be required if the driver asks for an exclusion
545	 * region, a data alignment that is stricter than 1, or DMA that begins
546	 * or ends with a partial cacheline.  Whether bouncing will actually
547	 * happen can't be known until mapping time, but we need to pre-allocate
548	 * resources now because we might not be allowed to at mapping time.
549	 */
550	if (dmat->flags & BUS_DMA_COULD_BOUNCE) {
551
552		/* Must bounce */
553		struct bounce_zone *bz;
554		int maxpages;
555
556		if (dmat->bounce_zone == NULL) {
557			if ((error = alloc_bounce_zone(dmat)) != 0) {
558				free(map, M_BUSDMA);
559				*mapp = NULL;
560				return (error);
561			}
562		}
563		bz = dmat->bounce_zone;
564
565		/* Initialize the new map */
566		STAILQ_INIT(&((*mapp)->bpages));
567
568		/*
569		 * Attempt to add pages to our pool on a per-instance
570		 * basis up to a sane limit.
571		 */
572		maxpages = MAX_BPAGES;
573		if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0
574		 || (bz->map_count > 0 && bz->total_bpages < maxpages)) {
575			int pages;
576
577			pages = MAX(atop(dmat->maxsize), 1);
578			pages = MIN(maxpages - bz->total_bpages, pages);
579			pages = MAX(pages, 1);
580			if (alloc_bounce_pages(dmat, pages) < pages)
581				error = ENOMEM;
582
583			if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0) {
584				if (error == 0)
585					dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
586			} else {
587				error = 0;
588			}
589		}
590		bz->map_count++;
591	}
592	map->sync_count = 0;
593	CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
594	    __func__, dmat, dmat->flags, error);
595
596	return (0);
597}
598
599/*
600 * Destroy a handle for mapping from kva/uva/physical
601 * address space into bus device space.
602 */
603int
604bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
605{
606
607	if (STAILQ_FIRST(&map->bpages) != NULL || map->sync_count != 0) {
608		CTR3(KTR_BUSDMA, "%s: tag %p error %d",
609		    __func__, dmat, EBUSY);
610		return (EBUSY);
611	}
612	if (dmat->bounce_zone)
613		dmat->bounce_zone->map_count--;
614	free(map, M_BUSDMA);
615	dmat->map_count--;
616	CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
617	return (0);
618}
619
620/*
621 * Allocate a piece of memory that can be efficiently mapped into bus device
622 * space based on the constraints listed in the dma tag.  Returns a pointer to
623 * the allocated memory, and a pointer to an associated bus_dmamap.
624 */
625int
626bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
627    bus_dmamap_t *mapp)
628{
629	busdma_bufalloc_t ba;
630	struct busdma_bufzone *bufzone;
631	bus_dmamap_t map;
632	vm_memattr_t memattr;
633	int mflags;
634
635	if (flags & BUS_DMA_NOWAIT)
636		mflags = M_NOWAIT;
637	else
638		mflags = M_WAITOK;
639	if (flags & BUS_DMA_ZERO)
640		mflags |= M_ZERO;
641
642	*mapp = map = allocate_map(dmat, mflags);
643	if (map == NULL) {
644		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
645		    __func__, dmat, dmat->flags, ENOMEM);
646		return (ENOMEM);
647	}
648	map->flags = DMAMAP_DMAMEM_ALLOC;
649
650	/* Choose a busdma buffer allocator based on memory type flags. */
651	if (flags & BUS_DMA_COHERENT) {
652		memattr = VM_MEMATTR_UNCACHEABLE;
653		ba = coherent_allocator;
654		map->flags |= DMAMAP_COHERENT;
655	} else {
656		memattr = VM_MEMATTR_DEFAULT;
657		ba = standard_allocator;
658	}
659
660	/*
661	 * Try to find a bufzone in the allocator that holds a cache of buffers
662	 * of the right size for this request.  If the buffer is too big to be
663	 * held in the allocator cache, this returns NULL.
664	 */
665	bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
666
667	/*
668	 * Allocate the buffer from the uma(9) allocator if...
669	 *  - It's small enough to be in the allocator (bufzone not NULL).
670	 *  - The alignment constraint isn't larger than the allocation size
671	 *    (the allocator aligns buffers to their size boundaries).
672	 *  - There's no need to handle lowaddr/highaddr exclusion zones.
673	 * else allocate non-contiguous pages if...
674	 *  - The page count that could get allocated doesn't exceed nsegments.
675	 *  - The alignment constraint isn't larger than a page boundary.
676	 *  - There are no boundary-crossing constraints.
677	 * else allocate a block of contiguous pages because one or more of the
678	 * constraints is something that only the contig allocator can fulfill.
679	 */
680	if (bufzone != NULL && dmat->alignment <= bufzone->size &&
681	    !_bus_dma_can_bounce(dmat->lowaddr, dmat->highaddr)) {
682		*vaddr = uma_zalloc(bufzone->umazone, mflags);
683	} else if (dmat->nsegments >= btoc(dmat->maxsize) &&
684	    dmat->alignment <= PAGE_SIZE && dmat->boundary == 0) {
685		*vaddr = (void *)kmem_alloc_attr(kernel_arena, dmat->maxsize,
686		    mflags, 0, dmat->lowaddr, memattr);
687	} else {
688		*vaddr = (void *)kmem_alloc_contig(kernel_arena, dmat->maxsize,
689		    mflags, 0, dmat->lowaddr, dmat->alignment, dmat->boundary,
690		    memattr);
691	}
692	if (*vaddr == NULL) {
693		CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
694		    __func__, dmat, dmat->flags, ENOMEM);
695		free(map, M_BUSDMA);
696		*mapp = NULL;
697		return (ENOMEM);
698	}
699	dmat->map_count++;
700
701	CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
702	    __func__, dmat, dmat->flags, 0);
703	return (0);
704}
705
706/*
707 * Free a piece of memory that was allocated via bus_dmamem_alloc, along with
708 * its associated map.
709 */
710void
711bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
712{
713	struct busdma_bufzone *bufzone;
714	busdma_bufalloc_t ba;
715
716	if (map->flags & DMAMAP_COHERENT)
717		ba = coherent_allocator;
718	else
719		ba = standard_allocator;
720
721	bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
722
723	if (bufzone != NULL && dmat->alignment <= bufzone->size &&
724	    !_bus_dma_can_bounce(dmat->lowaddr, dmat->highaddr))
725		uma_zfree(bufzone->umazone, vaddr);
726	else
727		kmem_free(kernel_arena, (vm_offset_t)vaddr, dmat->maxsize);
728
729	dmat->map_count--;
730	free(map, M_BUSDMA);
731	CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat, dmat->flags);
732}
733
734static void
735_bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
736    bus_size_t buflen, int flags)
737{
738	bus_addr_t curaddr;
739	bus_size_t sgsize;
740
741	if (map->pagesneeded == 0) {
742		CTR3(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d",
743		    dmat->lowaddr, dmat->boundary, dmat->alignment);
744		CTR2(KTR_BUSDMA, "map= %p, pagesneeded= %d",
745		    map, map->pagesneeded);
746		/*
747		 * Count the number of bounce pages
748		 * needed in order to complete this transfer
749		 */
750		curaddr = buf;
751		while (buflen != 0) {
752			sgsize = MIN(buflen, dmat->maxsegsz);
753			if (run_filter(dmat, curaddr) != 0) {
754				sgsize = MIN(sgsize,
755				    PAGE_SIZE - (curaddr & PAGE_MASK));
756				map->pagesneeded++;
757			}
758			curaddr += sgsize;
759			buflen -= sgsize;
760		}
761		CTR1(KTR_BUSDMA, "pagesneeded= %d\n", map->pagesneeded);
762	}
763}
764
765static void
766_bus_dmamap_count_pages(bus_dma_tag_t dmat, bus_dmamap_t map, pmap_t pmap,
767    void *buf, bus_size_t buflen, int flags)
768{
769	vm_offset_t vaddr;
770	vm_offset_t vendaddr;
771	bus_addr_t paddr;
772
773	if (map->pagesneeded == 0) {
774		CTR3(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d",
775		    dmat->lowaddr, dmat->boundary, dmat->alignment);
776		CTR2(KTR_BUSDMA, "map= %p, pagesneeded= %d",
777		    map, map->pagesneeded);
778		/*
779		 * Count the number of bounce pages
780		 * needed in order to complete this transfer
781		 */
782		vaddr = trunc_page((vm_offset_t)buf);
783		vendaddr = (vm_offset_t)buf + buflen;
784
785		while (vaddr < vendaddr) {
786			if (__predict_true(pmap == kernel_pmap))
787				paddr = pmap_kextract(vaddr);
788			else
789				paddr = pmap_extract(pmap, vaddr);
790			if (run_filter(dmat, paddr) != 0)
791				map->pagesneeded++;
792			vaddr += PAGE_SIZE;
793		}
794		CTR1(KTR_BUSDMA, "pagesneeded= %d\n", map->pagesneeded);
795	}
796}
797
798static int
799_bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int flags)
800{
801
802	/* Reserve Necessary Bounce Pages */
803	mtx_lock(&bounce_lock);
804	if (flags & BUS_DMA_NOWAIT) {
805		if (reserve_bounce_pages(dmat, map, 0) != 0) {
806			mtx_unlock(&bounce_lock);
807			return (ENOMEM);
808		}
809	} else {
810		if (reserve_bounce_pages(dmat, map, 1) != 0) {
811			/* Queue us for resources */
812			STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
813			mtx_unlock(&bounce_lock);
814			return (EINPROGRESS);
815		}
816	}
817	mtx_unlock(&bounce_lock);
818
819	return (0);
820}
821
822/*
823 * Add a single contiguous physical range to the segment list.
824 */
825static int
826_bus_dmamap_addseg(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t curaddr,
827    bus_size_t sgsize, bus_dma_segment_t *segs, int *segp)
828{
829	bus_addr_t baddr, bmask;
830	int seg;
831
832	/*
833	 * Make sure we don't cross any boundaries.
834	 */
835	bmask = ~(dmat->boundary - 1);
836	if (dmat->boundary > 0) {
837		baddr = (curaddr + dmat->boundary) & bmask;
838		if (sgsize > (baddr - curaddr))
839			sgsize = (baddr - curaddr);
840	}
841	if (dmat->ranges) {
842		struct arm32_dma_range *dr;
843
844		dr = _bus_dma_inrange(dmat->ranges, dmat->_nranges,
845		    curaddr);
846		if (dr == NULL)
847			return (0);
848		/*
849		 * In a valid DMA range.  Translate the physical
850		 * memory address to an address in the DMA window.
851		 */
852		curaddr = (curaddr - dr->dr_sysbase) + dr->dr_busbase;
853
854	}
855
856	seg = *segp;
857	/*
858	 * Insert chunk into a segment, coalescing with
859	 * the previous segment if possible.
860	 */
861	if (seg >= 0 &&
862	    curaddr == segs[seg].ds_addr + segs[seg].ds_len &&
863	    (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
864	    (dmat->boundary == 0 ||
865	    (segs[seg].ds_addr & bmask) == (curaddr & bmask))) {
866		segs[seg].ds_len += sgsize;
867	} else {
868		if (++seg >= dmat->nsegments)
869			return (0);
870		segs[seg].ds_addr = curaddr;
871		segs[seg].ds_len = sgsize;
872	}
873	*segp = seg;
874	return (sgsize);
875}
876
877/*
878 * Utility function to load a physical buffer.  segp contains
879 * the starting segment on entrace, and the ending segment on exit.
880 */
881int
882_bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
883    bus_size_t buflen, int flags, bus_dma_segment_t *segs, int *segp)
884{
885	struct sync_list *sl;
886	bus_size_t sgsize;
887	bus_addr_t curaddr;
888	bus_addr_t sl_end = 0;
889	int error;
890
891	if (segs == NULL)
892		segs = map->segments;
893
894	if ((dmat->flags & BUS_DMA_COULD_BOUNCE) != 0) {
895		_bus_dmamap_count_phys(dmat, map, buf, buflen, flags);
896		if (map->pagesneeded != 0) {
897			error = _bus_dmamap_reserve_pages(dmat, map, flags);
898			if (error)
899				return (error);
900		}
901	}
902
903	sl = map->slist + map->sync_count - 1;
904
905	while (buflen > 0) {
906		curaddr = buf;
907		sgsize = MIN(buflen, dmat->maxsegsz);
908		if (((dmat->flags & BUS_DMA_COULD_BOUNCE) != 0) &&
909		    map->pagesneeded != 0 && run_filter(dmat, curaddr)) {
910			sgsize = MIN(sgsize, PAGE_SIZE - (curaddr & PAGE_MASK));
911			curaddr = add_bounce_page(dmat, map, 0, curaddr,
912			    sgsize);
913		} else {
914			if (map->sync_count > 0)
915				sl_end = VM_PAGE_TO_PHYS(sl->pages) +
916				    sl->dataoffs + sl->datacount;
917
918			if (map->sync_count == 0 || curaddr != sl_end) {
919				if (++map->sync_count > dmat->nsegments)
920					break;
921				sl++;
922				sl->vaddr = 0;
923				sl->datacount = sgsize;
924				sl->pages = PHYS_TO_VM_PAGE(curaddr);
925				sl->dataoffs = curaddr & PAGE_MASK;
926			} else
927				sl->datacount += sgsize;
928		}
929		sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
930		    segp);
931		if (sgsize == 0)
932			break;
933		buf += sgsize;
934		buflen -= sgsize;
935	}
936
937	/*
938	 * Did we fit?
939	 */
940	if (buflen != 0) {
941		_bus_dmamap_unload(dmat, map);
942		return (EFBIG); /* XXX better return value here? */
943	}
944	return (0);
945}
946
947int
948_bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map,
949    struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
950    bus_dma_segment_t *segs, int *segp)
951{
952
953	return (bus_dmamap_load_ma_triv(dmat, map, ma, tlen, ma_offs, flags,
954	    segs, segp));
955}
956
957/*
958 * Utility function to load a linear buffer.  segp contains
959 * the starting segment on entrance, and the ending segment on exit.
960 */
961int
962_bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
963    bus_size_t buflen, struct pmap *pmap, int flags, bus_dma_segment_t *segs,
964    int *segp)
965{
966	bus_size_t sgsize;
967	bus_addr_t curaddr;
968	bus_addr_t sl_pend = 0;
969	struct sync_list *sl;
970	vm_offset_t kvaddr;
971	vm_offset_t vaddr = (vm_offset_t)buf;
972	vm_offset_t sl_vend = 0;
973	int error = 0;
974
975	if (segs == NULL)
976		segs = map->segments;
977	if ((flags & BUS_DMA_LOAD_MBUF) != 0)
978		map->flags |= DMAMAP_CACHE_ALIGNED;
979
980	if ((dmat->flags & BUS_DMA_COULD_BOUNCE) != 0) {
981		_bus_dmamap_count_pages(dmat, map, pmap, buf, buflen, flags);
982		if (map->pagesneeded != 0) {
983			error = _bus_dmamap_reserve_pages(dmat, map, flags);
984			if (error)
985				return (error);
986		}
987	}
988	CTR3(KTR_BUSDMA, "lowaddr= %d boundary= %d, "
989	    "alignment= %d", dmat->lowaddr, dmat->boundary, dmat->alignment);
990
991	sl = map->slist + map->sync_count - 1;
992
993	while (buflen > 0) {
994		/*
995		 * Get the physical address for this segment.
996		 */
997		if (__predict_true(pmap == kernel_pmap)) {
998			curaddr = pmap_kextract(vaddr);
999			kvaddr = vaddr;
1000		} else {
1001			curaddr = pmap_extract(pmap, vaddr);
1002			map->flags &= ~DMAMAP_COHERENT;
1003			kvaddr = 0;
1004		}
1005
1006		/*
1007		 * Compute the segment size, and adjust counts.
1008		 */
1009		sgsize = PAGE_SIZE - (curaddr & PAGE_MASK);
1010		if (sgsize > dmat->maxsegsz)
1011			sgsize = dmat->maxsegsz;
1012		if (buflen < sgsize)
1013			sgsize = buflen;
1014
1015		if (((dmat->flags & BUS_DMA_COULD_BOUNCE) != 0) &&
1016		    map->pagesneeded != 0 && run_filter(dmat, curaddr)) {
1017			curaddr = add_bounce_page(dmat, map, kvaddr, curaddr,
1018			    sgsize);
1019		} else {
1020			if (map->sync_count > 0) {
1021				sl_pend = VM_PAGE_TO_PHYS(sl->pages) +
1022				    sl->dataoffs + sl->datacount;
1023				sl_vend = sl->vaddr + sl->datacount;
1024			}
1025
1026			if (map->sync_count == 0 ||
1027			    (kvaddr != 0 && kvaddr != sl_vend) ||
1028			    (kvaddr == 0 && curaddr != sl_pend)) {
1029
1030				if (++map->sync_count > dmat->nsegments)
1031					goto cleanup;
1032				sl++;
1033				sl->vaddr = kvaddr;
1034				sl->datacount = sgsize;
1035				sl->pages = PHYS_TO_VM_PAGE(curaddr);
1036				sl->dataoffs = curaddr & PAGE_MASK;
1037			} else
1038				sl->datacount += sgsize;
1039		}
1040		sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1041		    segp);
1042		if (sgsize == 0)
1043			break;
1044		vaddr += sgsize;
1045		buflen -= sgsize;
1046	}
1047
1048cleanup:
1049	/*
1050	 * Did we fit?
1051	 */
1052	if (buflen != 0) {
1053		_bus_dmamap_unload(dmat, map);
1054		return (EFBIG); /* XXX better return value here? */
1055	}
1056	return (0);
1057}
1058
1059void
1060__bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map, struct memdesc *mem,
1061    bus_dmamap_callback_t *callback, void *callback_arg)
1062{
1063
1064	KASSERT(dmat != NULL, ("dmatag is NULL"));
1065	KASSERT(map != NULL, ("dmamap is NULL"));
1066	map->mem = *mem;
1067	map->callback = callback;
1068	map->callback_arg = callback_arg;
1069}
1070
1071bus_dma_segment_t *
1072_bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map,
1073    bus_dma_segment_t *segs, int nsegs, int error)
1074{
1075
1076	if (segs == NULL)
1077		segs = map->segments;
1078	return (segs);
1079}
1080
1081/*
1082 * Release the mapping held by map.
1083 */
1084void
1085_bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1086{
1087	struct bounce_page *bpage;
1088	struct bounce_zone *bz;
1089
1090	if ((bz = dmat->bounce_zone) != NULL) {
1091		while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1092			STAILQ_REMOVE_HEAD(&map->bpages, links);
1093			free_bounce_page(dmat, bpage);
1094		}
1095
1096		bz = dmat->bounce_zone;
1097		bz->free_bpages += map->pagesreserved;
1098		bz->reserved_bpages -= map->pagesreserved;
1099		map->pagesreserved = 0;
1100		map->pagesneeded = 0;
1101	}
1102	map->sync_count = 0;
1103	map->flags &= ~DMAMAP_MBUF;
1104}
1105
1106static void
1107bus_dmamap_sync_buf(vm_offset_t buf, int len, bus_dmasync_op_t op,
1108    int bufaligned)
1109{
1110	char _tmp_cl[arm_dcache_align], _tmp_clend[arm_dcache_align];
1111	register_t s;
1112	int partial;
1113
1114	if ((op & BUS_DMASYNC_PREWRITE) && !(op & BUS_DMASYNC_PREREAD)) {
1115		cpu_dcache_wb_range(buf, len);
1116		cpu_l2cache_wb_range(buf, len);
1117	}
1118
1119	/*
1120	 * If the caller promises the buffer is properly aligned to a cache line
1121	 * (even if the call parms make it look like it isn't) we can avoid
1122	 * attempting to preserve the non-DMA part of the cache line in the
1123	 * POSTREAD case, but we MUST still do a writeback in the PREREAD case.
1124	 *
1125	 * This covers the case of mbufs, where we know how they're aligned and
1126	 * know the CPU doesn't touch the header in front of the DMA data area
1127	 * during the IO, but it may have touched it right before invoking the
1128	 * sync, so a PREREAD writeback is required.
1129	 *
1130	 * It also handles buffers we created in bus_dmamem_alloc(), which are
1131	 * always aligned and padded to cache line size even if the IO length
1132	 * isn't a multiple of cache line size.  In this case the PREREAD
1133	 * writeback probably isn't required, but it's harmless.
1134	 */
1135	partial = (((vm_offset_t)buf) | len) & arm_dcache_align_mask;
1136
1137	if (op & BUS_DMASYNC_PREREAD) {
1138		if (!(op & BUS_DMASYNC_PREWRITE) && !partial) {
1139			cpu_dcache_inv_range(buf, len);
1140			cpu_l2cache_inv_range(buf, len);
1141		} else {
1142		    	cpu_dcache_wbinv_range(buf, len);
1143	    		cpu_l2cache_wbinv_range(buf, len);
1144		}
1145	}
1146	if (op & BUS_DMASYNC_POSTREAD) {
1147		if (partial && !bufaligned) {
1148			s = intr_disable();
1149			if (buf & arm_dcache_align_mask)
1150				memcpy(_tmp_cl, (void *)(buf &
1151				    ~arm_dcache_align_mask),
1152				    buf & arm_dcache_align_mask);
1153			if ((buf + len) & arm_dcache_align_mask)
1154				memcpy(_tmp_clend,
1155				    (void *)(buf + len),
1156				    arm_dcache_align -
1157				    ((buf + len) & arm_dcache_align_mask));
1158		}
1159		cpu_dcache_inv_range(buf, len);
1160		cpu_l2cache_inv_range(buf, len);
1161		if (partial && !bufaligned) {
1162			if (buf & arm_dcache_align_mask)
1163				memcpy((void *)(buf &
1164				    ~arm_dcache_align_mask), _tmp_cl,
1165				    buf & arm_dcache_align_mask);
1166			if ((buf + len) & arm_dcache_align_mask)
1167				memcpy((void *)(buf + len),
1168				    _tmp_clend, arm_dcache_align -
1169				    ((buf + len) & arm_dcache_align_mask));
1170			intr_restore(s);
1171		}
1172	}
1173}
1174
1175static void
1176bus_dmamap_sync_sl(struct sync_list *sl, bus_dmasync_op_t op,
1177    int bufaligned)
1178{
1179	vm_offset_t tempvaddr;
1180	vm_page_t curpage;
1181	size_t npages;
1182
1183	if (sl->vaddr != 0) {
1184		bus_dmamap_sync_buf(sl->vaddr, sl->datacount, op, bufaligned);
1185		return;
1186	}
1187
1188	tempvaddr = 0;
1189	npages = atop(round_page(sl->dataoffs + sl->datacount));
1190
1191	for (curpage = sl->pages; curpage != sl->pages + npages; ++curpage) {
1192		/*
1193		 * If the page is mapped to some other VA that hasn't
1194		 * been supplied to busdma, then pmap_quick_enter_page()
1195		 * will find all duplicate mappings and mark them
1196		 * uncacheable.
1197		 * That will also do any necessary wb/inv.  Otherwise,
1198		 * if the page is truly unmapped, then we don't actually
1199		 * need to do cache maintenance.
1200		 * XXX: May overwrite DMA'ed data in the POSTREAD
1201		 * case where the CPU has written to a cacheline not
1202		 * completely covered by the DMA region.
1203		 */
1204		KASSERT(VM_PAGE_TO_PHYS(curpage) == VM_PAGE_TO_PHYS(sl->pages) +
1205		    ptoa(curpage - sl->pages),
1206		    ("unexpected vm_page_t phys: 0x%08x != 0x%08x",
1207		    VM_PAGE_TO_PHYS(curpage), VM_PAGE_TO_PHYS(sl->pages) +
1208		    ptoa(curpage - sl->pages)));
1209		tempvaddr = pmap_quick_enter_page(curpage);
1210		pmap_quick_remove_page(tempvaddr);
1211	}
1212}
1213
1214static void
1215_bus_dmamap_sync_bp(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1216{
1217	struct bounce_page *bpage;
1218	vm_offset_t datavaddr, tempvaddr;
1219
1220	if ((op & (BUS_DMASYNC_PREWRITE | BUS_DMASYNC_POSTREAD)) == 0)
1221		return;
1222
1223	STAILQ_FOREACH(bpage, &map->bpages, links) {
1224		tempvaddr = 0;
1225		datavaddr = bpage->datavaddr;
1226		if (op & BUS_DMASYNC_PREWRITE) {
1227			if (datavaddr == 0) {
1228				tempvaddr =
1229				    pmap_quick_enter_page(bpage->datapage);
1230				datavaddr = tempvaddr | bpage->dataoffs;
1231			}
1232			bcopy((void *)datavaddr,
1233			    (void *)bpage->vaddr, bpage->datacount);
1234			if (tempvaddr != 0)
1235				pmap_quick_remove_page(tempvaddr);
1236			cpu_dcache_wb_range(bpage->vaddr, bpage->datacount);
1237			cpu_l2cache_wb_range(bpage->vaddr, bpage->datacount);
1238			dmat->bounce_zone->total_bounced++;
1239		}
1240		if (op & BUS_DMASYNC_POSTREAD) {
1241			cpu_dcache_inv_range(bpage->vaddr, bpage->datacount);
1242			cpu_l2cache_inv_range(bpage->vaddr, bpage->datacount);
1243			if (datavaddr == 0) {
1244				tempvaddr =
1245				    pmap_quick_enter_page(bpage->datapage);
1246				datavaddr = tempvaddr | bpage->dataoffs;
1247			}
1248			bcopy((void *)bpage->vaddr,
1249			    (void *)datavaddr, bpage->datacount);
1250			if (tempvaddr != 0)
1251				pmap_quick_remove_page(tempvaddr);
1252			dmat->bounce_zone->total_bounced++;
1253		}
1254	}
1255}
1256
1257void
1258_bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1259{
1260	struct sync_list *sl, *end;
1261	int bufaligned;
1262
1263	if (op == BUS_DMASYNC_POSTWRITE)
1264		return;
1265	if (map->flags & DMAMAP_COHERENT)
1266		goto drain;
1267	if (STAILQ_FIRST(&map->bpages))
1268		_bus_dmamap_sync_bp(dmat, map, op);
1269	CTR3(KTR_BUSDMA, "%s: op %x flags %x", __func__, op, map->flags);
1270	bufaligned = (map->flags & DMAMAP_CACHE_ALIGNED);
1271	if (map->sync_count) {
1272		end = &map->slist[map->sync_count];
1273		for (sl = &map->slist[0]; sl != end; sl++)
1274			bus_dmamap_sync_sl(sl, op, bufaligned);
1275	}
1276
1277drain:
1278
1279	cpu_drain_writebuf();
1280}
1281
1282static void
1283init_bounce_pages(void *dummy __unused)
1284{
1285
1286	total_bpages = 0;
1287	STAILQ_INIT(&bounce_zone_list);
1288	STAILQ_INIT(&bounce_map_waitinglist);
1289	STAILQ_INIT(&bounce_map_callbacklist);
1290	mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
1291}
1292SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
1293
1294static struct sysctl_ctx_list *
1295busdma_sysctl_tree(struct bounce_zone *bz)
1296{
1297
1298	return (&bz->sysctl_tree);
1299}
1300
1301static struct sysctl_oid *
1302busdma_sysctl_tree_top(struct bounce_zone *bz)
1303{
1304
1305	return (bz->sysctl_tree_top);
1306}
1307
1308static int
1309alloc_bounce_zone(bus_dma_tag_t dmat)
1310{
1311	struct bounce_zone *bz;
1312
1313	/* Check to see if we already have a suitable zone */
1314	STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1315		if ((dmat->alignment <= bz->alignment) &&
1316		    (dmat->lowaddr >= bz->lowaddr)) {
1317			dmat->bounce_zone = bz;
1318			return (0);
1319		}
1320	}
1321
1322	if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_BUSDMA,
1323	    M_NOWAIT | M_ZERO)) == NULL)
1324		return (ENOMEM);
1325
1326	STAILQ_INIT(&bz->bounce_page_list);
1327	bz->free_bpages = 0;
1328	bz->reserved_bpages = 0;
1329	bz->active_bpages = 0;
1330	bz->lowaddr = dmat->lowaddr;
1331	bz->alignment = MAX(dmat->alignment, PAGE_SIZE);
1332	bz->map_count = 0;
1333	snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1334	busdma_zonecount++;
1335	snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1336	STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1337	dmat->bounce_zone = bz;
1338
1339	sysctl_ctx_init(&bz->sysctl_tree);
1340	bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
1341	    SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1342	    CTLFLAG_RD, 0, "");
1343	if (bz->sysctl_tree_top == NULL) {
1344		sysctl_ctx_free(&bz->sysctl_tree);
1345		return (0);	/* XXX error code? */
1346	}
1347
1348	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1349	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1350	    "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1351	    "Total bounce pages");
1352	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1353	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1354	    "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1355	    "Free bounce pages");
1356	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1357	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1358	    "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1359	    "Reserved bounce pages");
1360	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1361	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1362	    "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1363	    "Active bounce pages");
1364	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1365	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1366	    "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1367	    "Total bounce requests (pages bounced)");
1368	SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1369	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1370	    "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1371	    "Total bounce requests that were deferred");
1372	SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1373	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1374	    "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1375	SYSCTL_ADD_ULONG(busdma_sysctl_tree(bz),
1376	    SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1377	    "alignment", CTLFLAG_RD, &bz->alignment, "");
1378
1379	return (0);
1380}
1381
1382static int
1383alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1384{
1385	struct bounce_zone *bz;
1386	int count;
1387
1388	bz = dmat->bounce_zone;
1389	count = 0;
1390	while (numpages > 0) {
1391		struct bounce_page *bpage;
1392
1393		bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_BUSDMA,
1394		    M_NOWAIT | M_ZERO);
1395
1396		if (bpage == NULL)
1397			break;
1398		bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_BOUNCE,
1399		    M_NOWAIT, 0ul, bz->lowaddr, PAGE_SIZE, 0);
1400		if (bpage->vaddr == 0) {
1401			free(bpage, M_BUSDMA);
1402			break;
1403		}
1404		bpage->busaddr = pmap_kextract(bpage->vaddr);
1405		mtx_lock(&bounce_lock);
1406		STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1407		total_bpages++;
1408		bz->total_bpages++;
1409		bz->free_bpages++;
1410		mtx_unlock(&bounce_lock);
1411		count++;
1412		numpages--;
1413	}
1414	return (count);
1415}
1416
1417static int
1418reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1419{
1420	struct bounce_zone *bz;
1421	int pages;
1422
1423	mtx_assert(&bounce_lock, MA_OWNED);
1424	bz = dmat->bounce_zone;
1425	pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1426	if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1427		return (map->pagesneeded - (map->pagesreserved + pages));
1428	bz->free_bpages -= pages;
1429	bz->reserved_bpages += pages;
1430	map->pagesreserved += pages;
1431	pages = map->pagesneeded - map->pagesreserved;
1432
1433	return (pages);
1434}
1435
1436static bus_addr_t
1437add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1438    bus_addr_t addr, bus_size_t size)
1439{
1440	struct bounce_zone *bz;
1441	struct bounce_page *bpage;
1442
1443	KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1444	KASSERT(map != NULL, ("add_bounce_page: bad map %p", map));
1445
1446	bz = dmat->bounce_zone;
1447	if (map->pagesneeded == 0)
1448		panic("add_bounce_page: map doesn't need any pages");
1449	map->pagesneeded--;
1450
1451	if (map->pagesreserved == 0)
1452		panic("add_bounce_page: map doesn't need any pages");
1453	map->pagesreserved--;
1454
1455	mtx_lock(&bounce_lock);
1456	bpage = STAILQ_FIRST(&bz->bounce_page_list);
1457	if (bpage == NULL)
1458		panic("add_bounce_page: free page list is empty");
1459
1460	STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1461	bz->reserved_bpages--;
1462	bz->active_bpages++;
1463	mtx_unlock(&bounce_lock);
1464
1465	if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1466		/* Page offset needs to be preserved. */
1467		bpage->vaddr |= addr & PAGE_MASK;
1468		bpage->busaddr |= addr & PAGE_MASK;
1469	}
1470	bpage->datavaddr = vaddr;
1471	bpage->datapage = PHYS_TO_VM_PAGE(addr);
1472	bpage->dataoffs = addr & PAGE_MASK;
1473	bpage->datacount = size;
1474	STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1475	return (bpage->busaddr);
1476}
1477
1478static void
1479free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1480{
1481	struct bus_dmamap *map;
1482	struct bounce_zone *bz;
1483
1484	bz = dmat->bounce_zone;
1485	bpage->datavaddr = 0;
1486	bpage->datacount = 0;
1487	if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1488		/*
1489		 * Reset the bounce page to start at offset 0.  Other uses
1490		 * of this bounce page may need to store a full page of
1491		 * data and/or assume it starts on a page boundary.
1492		 */
1493		bpage->vaddr &= ~PAGE_MASK;
1494		bpage->busaddr &= ~PAGE_MASK;
1495	}
1496
1497	mtx_lock(&bounce_lock);
1498	STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1499	bz->free_bpages++;
1500	bz->active_bpages--;
1501	if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1502		if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1503			STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1504			STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1505			    map, links);
1506			busdma_swi_pending = 1;
1507			bz->total_deferred++;
1508			swi_sched(vm_ih, 0);
1509		}
1510	}
1511	mtx_unlock(&bounce_lock);
1512}
1513
1514void
1515busdma_swi(void)
1516{
1517	bus_dma_tag_t dmat;
1518	struct bus_dmamap *map;
1519
1520	mtx_lock(&bounce_lock);
1521	while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1522		STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1523		mtx_unlock(&bounce_lock);
1524		dmat = map->dmat;
1525		dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_LOCK);
1526		bus_dmamap_load_mem(map->dmat, map, &map->mem, map->callback,
1527		    map->callback_arg, BUS_DMA_WAITOK);
1528		dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_UNLOCK);
1529		mtx_lock(&bounce_lock);
1530	}
1531	mtx_unlock(&bounce_lock);
1532}
1533