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