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.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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.
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
30 * From i386/busdma_machdep.c 191438 2009-04-23 20:24:19Z jhb
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/malloc.h>
40 #include <sys/busdma_bufalloc.h>
41 #include <sys/counter.h>
42 #include <sys/interrupt.h>
43 #include <sys/kernel.h>
46 #include <sys/memdesc.h>
48 #include <sys/mutex.h>
49 #include <sys/sysctl.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>
58 #include <machine/atomic.h>
59 #include <machine/bus.h>
60 #include <machine/cpu-v6.h>
61 #include <machine/md_var.h>
63 #define BUSDMA_DCACHE_ALIGN cpuinfo.dcache_line_size
64 #define BUSDMA_DCACHE_MASK cpuinfo.dcache_line_mask
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
81 bus_dma_filter_t *filter;
89 bus_dma_lock_t *lockfunc;
91 struct bounce_zone *bounce_zone;
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;
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 */
111 int busdma_swi_pending;
114 STAILQ_ENTRY(bounce_zone) links;
115 STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
123 bus_size_t alignment;
127 struct sysctl_ctx_list sysctl_tree;
128 struct sysctl_oid *sysctl_tree_top;
131 static struct mtx bounce_lock;
132 static int total_bpages;
133 static int busdma_zonecount;
134 static uint32_t tags_total;
135 static uint32_t maps_total;
136 static uint32_t maps_dmamem;
137 static uint32_t maps_coherent;
138 static counter_u64_t maploads_total;
139 static counter_u64_t maploads_bounced;
140 static counter_u64_t maploads_coherent;
141 static counter_u64_t maploads_dmamem;
142 static counter_u64_t maploads_mbuf;
143 static counter_u64_t maploads_physmem;
145 static STAILQ_HEAD(, bounce_zone) bounce_zone_list;
147 SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
148 SYSCTL_UINT(_hw_busdma, OID_AUTO, tags_total, CTLFLAG_RD, &tags_total, 0,
149 "Number of active tags");
150 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_total, CTLFLAG_RD, &maps_total, 0,
151 "Number of active maps");
152 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_dmamem, CTLFLAG_RD, &maps_dmamem, 0,
153 "Number of active maps for bus_dmamem_alloc buffers");
154 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_coherent, CTLFLAG_RD, &maps_coherent, 0,
155 "Number of active maps with BUS_DMA_COHERENT flag set");
156 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_total, CTLFLAG_RD,
157 &maploads_total, "Number of load operations performed");
158 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_bounced, CTLFLAG_RD,
159 &maploads_bounced, "Number of load operations that used bounce buffers");
160 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_coherent, CTLFLAG_RD,
161 &maploads_dmamem, "Number of load operations on BUS_DMA_COHERENT memory");
162 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_dmamem, CTLFLAG_RD,
163 &maploads_dmamem, "Number of load operations on bus_dmamem_alloc buffers");
164 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_mbuf, CTLFLAG_RD,
165 &maploads_mbuf, "Number of load operations for mbufs");
166 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_physmem, CTLFLAG_RD,
167 &maploads_physmem, "Number of load operations on physical buffers");
168 SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bpages, 0,
169 "Total bounce pages");
172 struct bp_list bpages;
177 bus_dmamap_callback_t *callback;
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;
186 struct sync_list slist[];
189 static STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
190 static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist;
192 static void init_bounce_pages(void *dummy);
193 static int alloc_bounce_zone(bus_dma_tag_t dmat);
194 static int alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages);
195 static int reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
197 static 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);
199 static void free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage);
200 static 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);
202 static 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);
204 static int _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
206 static void dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size);
207 static void dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op);
209 static busdma_bufalloc_t coherent_allocator; /* Cache of coherent buffers */
210 static busdma_bufalloc_t standard_allocator; /* Cache of standard buffers */
212 MALLOC_DEFINE(M_BUSDMA, "busdma", "busdma metadata");
213 MALLOC_DEFINE(M_BOUNCE, "bounce", "busdma bounce pages");
216 busdma_init(void *dummy)
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);
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 */
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
243 uma_flags = UMA_ZONE_OFFPAGE;
246 * Create a cache of buffers in uncacheable memory, to implement the
247 * BUS_DMA_COHERENT (and potentially BUS_DMA_NOCACHE) flag.
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 */
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.
262 SYSINIT(busdma, SI_SUB_KMEM+1, SI_ORDER_FIRST, busdma_init, NULL);
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).
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.
277 exclusion_bounce_check(vm_offset_t lowaddr, vm_offset_t highaddr)
281 if (lowaddr >= BUS_SPACE_MAXADDR)
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]))
293 * Return true if the tag has an exclusion zone that could lead to bouncing.
296 exclusion_bounce(bus_dma_tag_t dmat)
299 return (dmat->flags & BUS_DMA_EXCL_BOUNCE);
303 * Return true if the given address does not fall on the alignment boundary.
306 alignment_bounce(bus_dma_tag_t dmat, bus_addr_t addr)
309 return (addr & (dmat->alignment - 1));
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.
324 cacheline_bounce(bus_dmamap_t map, bus_addr_t addr, bus_size_t size)
327 if (map->flags & (DMAMAP_DMAMEM_ALLOC | DMAMAP_COHERENT | DMAMAP_MBUF))
329 return ((addr | size) & BUSDMA_DCACHE_MASK);
333 * Return true if we might need to bounce the DMA described by addr and size.
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.
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
343 might_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t addr,
347 return ((dmat->flags & BUS_DMA_EXCL_BOUNCE) ||
348 alignment_bounce(dmat, addr) ||
349 cacheline_bounce(map, addr, size));
353 * Return true if we must bounce the DMA described by paddr and size.
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.
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.
364 must_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t paddr,
368 if (cacheline_bounce(map, paddr, size))
372 * The tag already contains ancestors' alignment restrictions so this
373 * check doesn't need to be inside the loop.
375 if (alignment_bounce(dmat, paddr))
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.
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))
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.
403 busdma_lock_mutex(void *arg, bus_dma_lock_op_t op)
407 dmtx = (struct mtx *)arg;
416 panic("Unknown operation 0x%x for busdma_lock_mutex!", op);
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.
427 dflt_lock(void *arg, bus_dma_lock_op_t op)
430 panic("driver error: busdma dflt_lock called");
434 * Allocate a device specific dma_tag.
437 bus_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)
443 bus_dma_tag_t newtag;
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"));
455 /* Return a NULL tag on failure */
458 newtag = (bus_dma_tag_t)malloc(sizeof(*newtag), M_BUSDMA,
460 if (newtag == NULL) {
461 CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
462 __func__, newtag, 0, error);
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) +
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;
484 newtag->lockfunc = dflt_lock;
485 newtag->lockfuncarg = NULL;
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,
499 if (newtag->filter == NULL) {
501 * Short circuit to looking at our parent directly
502 * since we have encapsulated all of its information
504 newtag->filter = parent->filter;
505 newtag->filterarg = parent->filterarg;
506 newtag->parent = parent->parent;
508 if (newtag->parent != NULL)
509 atomic_add_int(&parent->ref_count, 1);
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;
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.
522 if ((flags & BUS_DMA_ALLOCNOW) != 0) {
523 struct bounce_zone *bz;
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.
529 maxsize = roundup2(maxsize, PAGE_SIZE) + PAGE_SIZE;
531 if ((error = alloc_bounce_zone(newtag)) != 0) {
532 free(newtag, M_BUSDMA);
535 bz = newtag->bounce_zone;
537 if (ptoa(bz->total_bpages) < maxsize) {
540 pages = atop(maxsize) - bz->total_bpages;
542 /* Add pages to our bounce pool */
543 if (alloc_bounce_pages(newtag, pages) < pages)
546 /* Performed initial allocation */
547 newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
549 newtag->bounce_zone = NULL;
552 free(newtag, M_BUSDMA);
554 atomic_add_32(&tags_total, 1);
557 CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
558 __func__, newtag, (newtag != NULL ? newtag->flags : 0), error);
563 bus_dma_tag_destroy(bus_dma_tag_t dmat)
565 bus_dma_tag_t dmat_copy;
573 if (dmat->map_count != 0) {
578 while (dmat != NULL) {
579 bus_dma_tag_t parent;
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);
587 * Last reference count, so
588 * release our reference
589 * count on our parent.
597 CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
602 allocate_bz_and_pages(bus_dma_tag_t dmat, bus_dmamap_t mapp)
604 struct bounce_zone *bz;
608 if (dmat->bounce_zone == NULL)
609 if ((error = alloc_bounce_zone(dmat)) != 0)
611 bz = dmat->bounce_zone;
612 /* Initialize the new map */
613 STAILQ_INIT(&(mapp->bpages));
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.
621 if (dmat->flags & BUS_DMA_COULD_BOUNCE)
622 maxpages = MAX_BPAGES;
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)) {
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)
635 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0)
636 dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
643 allocate_map(bus_dma_tag_t dmat, int mflags)
645 int mapsize, segsize;
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.
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);
660 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
663 map->segments = (bus_dma_segment_t *)((uintptr_t)map + mapsize);
668 * Allocate a handle for mapping from kva/uva/physical
669 * address space into bus device space.
672 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
677 *mapp = map = allocate_map(dmat, M_NOWAIT);
679 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
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.
690 error = allocate_bz_and_pages(dmat, map);
696 if (map->flags & DMAMAP_COHERENT)
697 atomic_add_32(&maps_coherent, 1);
698 atomic_add_32(&maps_total, 1);
705 * Destroy a handle for mapping from kva/uva/physical
706 * address space into bus device space.
709 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
712 if (STAILQ_FIRST(&map->bpages) != NULL || map->sync_count != 0) {
713 CTR3(KTR_BUSDMA, "%s: tag %p error %d",
714 __func__, dmat, EBUSY);
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);
724 CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
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.
734 bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
737 busdma_bufalloc_t ba;
738 struct busdma_bufzone *bufzone;
740 vm_memattr_t memattr;
743 if (flags & BUS_DMA_NOWAIT)
747 if (flags & BUS_DMA_ZERO)
750 *mapp = map = allocate_map(dmat, mflags);
752 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
753 __func__, dmat, dmat->flags, ENOMEM);
756 map->flags = DMAMAP_DMAMEM_ALLOC;
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;
764 memattr = VM_MEMATTR_DEFAULT;
765 ba = standard_allocator;
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.
773 bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
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 nsegments.
783 * - The alignment constraint isn't larger than a page boundary.
784 * - There are no boundary-crossing constraints.
785 * else allocate a block of contiguous pages because one or more of the
786 * constraints is something that only the contig allocator can fulfill.
788 if (bufzone != NULL && dmat->alignment <= bufzone->size &&
789 !exclusion_bounce(dmat)) {
790 *vaddr = uma_zalloc(bufzone->umazone, mflags);
791 } else if (dmat->nsegments >= btoc(dmat->maxsize) &&
792 dmat->alignment <= PAGE_SIZE && dmat->boundary == 0) {
793 *vaddr = (void *)kmem_alloc_attr(kernel_arena, dmat->maxsize,
794 mflags, 0, dmat->lowaddr, memattr);
796 *vaddr = (void *)kmem_alloc_contig(kernel_arena, dmat->maxsize,
797 mflags, 0, dmat->lowaddr, dmat->alignment, dmat->boundary,
800 if (*vaddr == NULL) {
801 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
802 __func__, dmat, dmat->flags, ENOMEM);
807 if (map->flags & DMAMAP_COHERENT)
808 atomic_add_32(&maps_coherent, 1);
809 atomic_add_32(&maps_dmamem, 1);
810 atomic_add_32(&maps_total, 1);
813 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
814 __func__, dmat, dmat->flags, 0);
819 * Free a piece of memory that was allocated via bus_dmamem_alloc, along with
820 * its associated map.
823 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
825 struct busdma_bufzone *bufzone;
826 busdma_bufalloc_t ba;
828 if (map->flags & DMAMAP_COHERENT)
829 ba = coherent_allocator;
831 ba = standard_allocator;
833 bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
835 if (bufzone != NULL && dmat->alignment <= bufzone->size &&
836 !exclusion_bounce(dmat))
837 uma_zfree(bufzone->umazone, vaddr);
839 kmem_free(kernel_arena, (vm_offset_t)vaddr, dmat->maxsize);
842 if (map->flags & DMAMAP_COHERENT)
843 atomic_subtract_32(&maps_coherent, 1);
844 atomic_subtract_32(&maps_total, 1);
845 atomic_subtract_32(&maps_dmamem, 1);
847 CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat, dmat->flags);
851 _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
852 bus_size_t buflen, int flags)
857 if (map->pagesneeded == 0) {
858 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
859 " map= %p, pagesneeded= %d",
860 dmat->lowaddr, dmat->boundary, dmat->alignment,
861 map, map->pagesneeded);
863 * Count the number of bounce pages
864 * needed in order to complete this transfer
867 while (buflen != 0) {
868 sgsize = MIN(buflen, dmat->maxsegsz);
869 if (must_bounce(dmat, map, curaddr, sgsize) != 0) {
871 PAGE_SIZE - (curaddr & PAGE_MASK));
877 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
882 _bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap, bus_dmamap_t map,
883 void *buf, bus_size_t buflen, int flags)
886 vm_offset_t vendaddr;
889 if (map->pagesneeded == 0) {
890 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
891 " map= %p, pagesneeded= %d",
892 dmat->lowaddr, dmat->boundary, dmat->alignment,
893 map, map->pagesneeded);
895 * Count the number of bounce pages
896 * needed in order to complete this transfer
898 vaddr = (vm_offset_t)buf;
899 vendaddr = (vm_offset_t)buf + buflen;
901 while (vaddr < vendaddr) {
902 if (__predict_true(pmap == kernel_pmap))
903 paddr = pmap_kextract(vaddr);
905 paddr = pmap_extract(pmap, vaddr);
906 if (must_bounce(dmat, map, paddr,
907 min(vendaddr - vaddr, (PAGE_SIZE - ((vm_offset_t)vaddr &
908 PAGE_MASK)))) != 0) {
911 vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
914 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
919 _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int flags)
922 /* Reserve Necessary Bounce Pages */
923 mtx_lock(&bounce_lock);
924 if (flags & BUS_DMA_NOWAIT) {
925 if (reserve_bounce_pages(dmat, map, 0) != 0) {
926 map->pagesneeded = 0;
927 mtx_unlock(&bounce_lock);
931 if (reserve_bounce_pages(dmat, map, 1) != 0) {
932 /* Queue us for resources */
933 STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
934 mtx_unlock(&bounce_lock);
935 return (EINPROGRESS);
938 mtx_unlock(&bounce_lock);
944 * Add a single contiguous physical range to the segment list.
947 _bus_dmamap_addseg(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t curaddr,
948 bus_size_t sgsize, bus_dma_segment_t *segs, int *segp)
950 bus_addr_t baddr, bmask;
954 * Make sure we don't cross any boundaries.
956 bmask = ~(dmat->boundary - 1);
957 if (dmat->boundary > 0) {
958 baddr = (curaddr + dmat->boundary) & bmask;
959 if (sgsize > (baddr - curaddr))
960 sgsize = (baddr - curaddr);
964 * Insert chunk into a segment, coalescing with
965 * previous segment if possible.
970 segs[seg].ds_addr = curaddr;
971 segs[seg].ds_len = sgsize;
973 if (curaddr == segs[seg].ds_addr + segs[seg].ds_len &&
974 (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
975 (dmat->boundary == 0 ||
976 (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
977 segs[seg].ds_len += sgsize;
979 if (++seg >= dmat->nsegments)
981 segs[seg].ds_addr = curaddr;
982 segs[seg].ds_len = sgsize;
990 * Utility function to load a physical buffer. segp contains
991 * the starting segment on entrace, and the ending segment on exit.
994 _bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
995 bus_size_t buflen, int flags, bus_dma_segment_t *segs, int *segp)
998 bus_addr_t sl_end = 0;
1000 struct sync_list *sl;
1004 segs = map->segments;
1006 counter_u64_add(maploads_total, 1);
1007 counter_u64_add(maploads_physmem, 1);
1009 if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1010 _bus_dmamap_count_phys(dmat, map, buf, buflen, flags);
1011 if (map->pagesneeded != 0) {
1012 counter_u64_add(maploads_bounced, 1);
1013 error = _bus_dmamap_reserve_pages(dmat, map, flags);
1019 sl = map->slist + map->sync_count - 1;
1021 while (buflen > 0) {
1023 sgsize = MIN(buflen, dmat->maxsegsz);
1024 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1026 sgsize = MIN(sgsize, PAGE_SIZE - (curaddr & PAGE_MASK));
1027 curaddr = add_bounce_page(dmat, map, 0, curaddr,
1030 if (map->sync_count > 0)
1031 sl_end = sl->paddr + sl->datacount;
1033 if (map->sync_count == 0 || curaddr != sl_end) {
1034 if (++map->sync_count > dmat->nsegments)
1038 sl->paddr = curaddr;
1039 sl->datacount = sgsize;
1040 sl->pages = PHYS_TO_VM_PAGE(curaddr);
1041 KASSERT(sl->pages != NULL,
1042 ("%s: page at PA:0x%08lx is not in "
1043 "vm_page_array", __func__, curaddr));
1045 sl->datacount += sgsize;
1047 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1059 _bus_dmamap_unload(dmat, map);
1060 return (EFBIG); /* XXX better return value here? */
1066 _bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map,
1067 struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
1068 bus_dma_segment_t *segs, int *segp)
1071 return (bus_dmamap_load_ma_triv(dmat, map, ma, tlen, ma_offs, flags,
1076 * Utility function to load a linear buffer. segp contains
1077 * the starting segment on entrance, and the ending segment on exit.
1080 _bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
1081 bus_size_t buflen, pmap_t pmap, int flags, bus_dma_segment_t *segs,
1086 bus_addr_t sl_pend = 0;
1087 vm_offset_t kvaddr, vaddr, sl_vend = 0;
1088 struct sync_list *sl;
1091 counter_u64_add(maploads_total, 1);
1092 if (map->flags & DMAMAP_COHERENT)
1093 counter_u64_add(maploads_coherent, 1);
1094 if (map->flags & DMAMAP_DMAMEM_ALLOC)
1095 counter_u64_add(maploads_dmamem, 1);
1098 segs = map->segments;
1100 if (flags & BUS_DMA_LOAD_MBUF) {
1101 counter_u64_add(maploads_mbuf, 1);
1102 map->flags |= DMAMAP_MBUF;
1105 if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1106 _bus_dmamap_count_pages(dmat, pmap, map, buf, buflen, flags);
1107 if (map->pagesneeded != 0) {
1108 counter_u64_add(maploads_bounced, 1);
1109 error = _bus_dmamap_reserve_pages(dmat, map, flags);
1115 sl = map->slist + map->sync_count - 1;
1116 vaddr = (vm_offset_t)buf;
1118 while (buflen > 0) {
1120 * Get the physical address for this segment.
1122 if (__predict_true(pmap == kernel_pmap)) {
1123 curaddr = pmap_kextract(vaddr);
1126 curaddr = pmap_extract(pmap, vaddr);
1131 * Compute the segment size, and adjust counts.
1133 sgsize = PAGE_SIZE - (curaddr & PAGE_MASK);
1134 if (sgsize > dmat->maxsegsz)
1135 sgsize = dmat->maxsegsz;
1136 if (buflen < sgsize)
1139 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1141 curaddr = add_bounce_page(dmat, map, kvaddr, curaddr,
1144 if (map->sync_count > 0) {
1145 sl_pend = sl->paddr + sl->datacount;
1146 sl_vend = sl->vaddr + sl->datacount;
1149 if (map->sync_count == 0 ||
1150 (kvaddr != 0 && kvaddr != sl_vend) ||
1151 (curaddr != sl_pend)) {
1153 if (++map->sync_count > dmat->nsegments)
1157 sl->paddr = curaddr;
1161 sl->pages = PHYS_TO_VM_PAGE(curaddr);
1162 KASSERT(sl->pages != NULL,
1163 ("%s: page at PA:0x%08lx is not "
1164 "in vm_page_array", __func__,
1167 sl->datacount = sgsize;
1169 sl->datacount += sgsize;
1171 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1184 _bus_dmamap_unload(dmat, map);
1185 return (EFBIG); /* XXX better return value here? */
1191 __bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map, struct memdesc *mem,
1192 bus_dmamap_callback_t *callback, void *callback_arg)
1197 map->callback = callback;
1198 map->callback_arg = callback_arg;
1202 _bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map,
1203 bus_dma_segment_t *segs, int nsegs, int error)
1207 segs = map->segments;
1212 * Release the mapping held by map.
1215 _bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1217 struct bounce_page *bpage;
1218 struct bounce_zone *bz;
1220 if ((bz = dmat->bounce_zone) != NULL) {
1221 while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1222 STAILQ_REMOVE_HEAD(&map->bpages, links);
1223 free_bounce_page(dmat, bpage);
1226 bz = dmat->bounce_zone;
1227 bz->free_bpages += map->pagesreserved;
1228 bz->reserved_bpages -= map->pagesreserved;
1229 map->pagesreserved = 0;
1230 map->pagesneeded = 0;
1232 map->sync_count = 0;
1233 map->flags &= ~DMAMAP_MBUF;
1237 dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size)
1240 * Write back any partial cachelines immediately before and
1241 * after the DMA region. We don't need to round the address
1242 * down to the nearest cacheline or specify the exact size,
1243 * as dcache_wb_poc() will do the rounding for us and works
1244 * at cacheline granularity.
1246 if (va & BUSDMA_DCACHE_MASK)
1247 dcache_wb_poc(va, pa, 1);
1248 if ((va + size) & BUSDMA_DCACHE_MASK)
1249 dcache_wb_poc(va + size, pa + size, 1);
1251 dcache_inv_poc_dma(va, pa, size);
1255 dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op)
1257 uint32_t len, offset;
1260 vm_offset_t va, tempva;
1263 offset = sl->paddr & PAGE_MASK;
1265 size = sl->datacount;
1268 for ( ; size != 0; size -= len, pa += len, offset = 0, ++m) {
1270 if (sl->vaddr == 0) {
1271 len = min(PAGE_SIZE - offset, size);
1272 tempva = pmap_quick_enter_page(m);
1273 va = tempva | offset;
1274 KASSERT(pa == (VM_PAGE_TO_PHYS(m) | offset),
1275 ("unexpected vm_page_t phys: 0x%08x != 0x%08x",
1276 VM_PAGE_TO_PHYS(m) | offset, pa));
1278 len = sl->datacount;
1283 case BUS_DMASYNC_PREWRITE:
1284 case BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD:
1285 dcache_wb_poc(va, pa, len);
1287 case BUS_DMASYNC_PREREAD:
1289 * An mbuf may start in the middle of a cacheline. There
1290 * will be no cpu writes to the beginning of that line
1291 * (which contains the mbuf header) while dma is in
1292 * progress. Handle that case by doing a writeback of
1293 * just the first cacheline before invalidating the
1294 * overall buffer. Any mbuf in a chain may have this
1295 * misalignment. Buffers which are not mbufs bounce if
1296 * they are not aligned to a cacheline.
1298 dma_preread_safe(va, pa, len);
1300 case BUS_DMASYNC_POSTREAD:
1301 case BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE:
1302 dcache_inv_poc(va, pa, len);
1305 panic("unsupported combination of sync operations: "
1310 pmap_quick_remove_page(tempva);
1315 _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1317 struct bounce_page *bpage;
1318 struct sync_list *sl, *end;
1319 vm_offset_t datavaddr, tempvaddr;
1321 if (op == BUS_DMASYNC_POSTWRITE)
1325 * If the buffer was from user space, it is possible that this is not
1326 * the same vm map, especially on a POST operation. It's not clear that
1327 * dma on userland buffers can work at all right now. To be safe, until
1328 * we're able to test direct userland dma, panic on a map mismatch.
1330 if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1332 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1333 "performing bounce", __func__, dmat, dmat->flags, op);
1336 * For PREWRITE do a writeback. Clean the caches from the
1337 * innermost to the outermost levels.
1339 if (op & BUS_DMASYNC_PREWRITE) {
1340 while (bpage != NULL) {
1342 datavaddr = bpage->datavaddr;
1343 if (datavaddr == 0) {
1344 tempvaddr = pmap_quick_enter_page(
1346 datavaddr = tempvaddr | bpage->dataoffs;
1348 bcopy((void *)datavaddr, (void *)bpage->vaddr,
1351 pmap_quick_remove_page(tempvaddr);
1352 dcache_wb_poc(bpage->vaddr, bpage->busaddr,
1354 bpage = STAILQ_NEXT(bpage, links);
1356 dmat->bounce_zone->total_bounced++;
1360 * Do an invalidate for PREREAD unless a writeback was already
1361 * done above due to PREWRITE also being set. The reason for a
1362 * PREREAD invalidate is to prevent dirty lines currently in the
1363 * cache from being evicted during the DMA. If a writeback was
1364 * done due to PREWRITE also being set there will be no dirty
1365 * lines and the POSTREAD invalidate handles the rest. The
1366 * invalidate is done from the innermost to outermost level. If
1367 * L2 were done first, a dirty cacheline could be automatically
1368 * evicted from L1 before we invalidated it, re-dirtying the L2.
1370 if ((op & BUS_DMASYNC_PREREAD) && !(op & BUS_DMASYNC_PREWRITE)) {
1371 bpage = STAILQ_FIRST(&map->bpages);
1372 while (bpage != NULL) {
1373 dcache_inv_poc_dma(bpage->vaddr, bpage->busaddr,
1375 bpage = STAILQ_NEXT(bpage, links);
1380 * Re-invalidate the caches on a POSTREAD, even though they were
1381 * already invalidated at PREREAD time. Aggressive prefetching
1382 * due to accesses to other data near the dma buffer could have
1383 * brought buffer data into the caches which is now stale. The
1384 * caches are invalidated from the outermost to innermost; the
1385 * prefetches could be happening right now, and if L1 were
1386 * invalidated first, stale L2 data could be prefetched into L1.
1388 if (op & BUS_DMASYNC_POSTREAD) {
1389 while (bpage != NULL) {
1390 dcache_inv_poc(bpage->vaddr, bpage->busaddr,
1393 datavaddr = bpage->datavaddr;
1394 if (datavaddr == 0) {
1395 tempvaddr = pmap_quick_enter_page(
1397 datavaddr = tempvaddr | bpage->dataoffs;
1399 bcopy((void *)bpage->vaddr, (void *)datavaddr,
1402 pmap_quick_remove_page(tempvaddr);
1403 bpage = STAILQ_NEXT(bpage, links);
1405 dmat->bounce_zone->total_bounced++;
1410 * For COHERENT memory no cache maintenance is necessary, but ensure all
1411 * writes have reached memory for the PREWRITE case. No action is
1412 * needed for a PREREAD without PREWRITE also set, because that would
1413 * imply that the cpu had written to the COHERENT buffer and expected
1414 * the dma device to see that change, and by definition a PREWRITE sync
1415 * is required to make that happen.
1417 if (map->flags & DMAMAP_COHERENT) {
1418 if (op & BUS_DMASYNC_PREWRITE) {
1420 cpu_l2cache_drain_writebuf();
1426 * Cache maintenance for normal (non-COHERENT non-bounce) buffers. All
1427 * the comments about the sequences for flushing cache levels in the
1428 * bounce buffer code above apply here as well. In particular, the fact
1429 * that the sequence is inner-to-outer for PREREAD invalidation and
1430 * outer-to-inner for POSTREAD invalidation is not a mistake.
1432 if (map->sync_count != 0) {
1433 sl = &map->slist[0];
1434 end = &map->slist[map->sync_count];
1435 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1436 "performing sync", __func__, dmat, dmat->flags, op);
1438 for ( ; sl != end; ++sl)
1439 dma_dcache_sync(sl, op);
1444 init_bounce_pages(void *dummy __unused)
1448 STAILQ_INIT(&bounce_zone_list);
1449 STAILQ_INIT(&bounce_map_waitinglist);
1450 STAILQ_INIT(&bounce_map_callbacklist);
1451 mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
1453 SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
1455 static struct sysctl_ctx_list *
1456 busdma_sysctl_tree(struct bounce_zone *bz)
1459 return (&bz->sysctl_tree);
1462 static struct sysctl_oid *
1463 busdma_sysctl_tree_top(struct bounce_zone *bz)
1466 return (bz->sysctl_tree_top);
1470 alloc_bounce_zone(bus_dma_tag_t dmat)
1472 struct bounce_zone *bz;
1474 /* Check to see if we already have a suitable zone */
1475 STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1476 if ((dmat->alignment <= bz->alignment) &&
1477 (dmat->lowaddr >= bz->lowaddr)) {
1478 dmat->bounce_zone = bz;
1483 if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_BUSDMA,
1484 M_NOWAIT | M_ZERO)) == NULL)
1487 STAILQ_INIT(&bz->bounce_page_list);
1488 bz->free_bpages = 0;
1489 bz->reserved_bpages = 0;
1490 bz->active_bpages = 0;
1491 bz->lowaddr = dmat->lowaddr;
1492 bz->alignment = MAX(dmat->alignment, PAGE_SIZE);
1494 snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1496 snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1497 STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1498 dmat->bounce_zone = bz;
1500 sysctl_ctx_init(&bz->sysctl_tree);
1501 bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
1502 SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1504 if (bz->sysctl_tree_top == NULL) {
1505 sysctl_ctx_free(&bz->sysctl_tree);
1506 return (0); /* XXX error code? */
1509 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1510 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1511 "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1512 "Total bounce pages");
1513 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1514 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1515 "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1516 "Free bounce pages");
1517 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1518 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1519 "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1520 "Reserved bounce pages");
1521 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1522 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1523 "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1524 "Active bounce pages");
1525 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1526 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1527 "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1528 "Total bounce requests (pages bounced)");
1529 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1530 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1531 "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1532 "Total bounce requests that were deferred");
1533 SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1534 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1535 "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1536 SYSCTL_ADD_ULONG(busdma_sysctl_tree(bz),
1537 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1538 "alignment", CTLFLAG_RD, &bz->alignment, "");
1544 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1546 struct bounce_zone *bz;
1549 bz = dmat->bounce_zone;
1551 while (numpages > 0) {
1552 struct bounce_page *bpage;
1554 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_BUSDMA,
1559 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_BOUNCE,
1560 M_NOWAIT, 0ul, bz->lowaddr, PAGE_SIZE, 0);
1561 if (bpage->vaddr == 0) {
1562 free(bpage, M_BUSDMA);
1565 bpage->busaddr = pmap_kextract(bpage->vaddr);
1566 mtx_lock(&bounce_lock);
1567 STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1571 mtx_unlock(&bounce_lock);
1579 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1581 struct bounce_zone *bz;
1584 mtx_assert(&bounce_lock, MA_OWNED);
1585 bz = dmat->bounce_zone;
1586 pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1587 if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1588 return (map->pagesneeded - (map->pagesreserved + pages));
1589 bz->free_bpages -= pages;
1590 bz->reserved_bpages += pages;
1591 map->pagesreserved += pages;
1592 pages = map->pagesneeded - map->pagesreserved;
1598 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1599 bus_addr_t addr, bus_size_t size)
1601 struct bounce_zone *bz;
1602 struct bounce_page *bpage;
1604 KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1605 KASSERT(map != NULL, ("add_bounce_page: bad map %p", map));
1607 bz = dmat->bounce_zone;
1608 if (map->pagesneeded == 0)
1609 panic("add_bounce_page: map doesn't need any pages");
1612 if (map->pagesreserved == 0)
1613 panic("add_bounce_page: map doesn't need any pages");
1614 map->pagesreserved--;
1616 mtx_lock(&bounce_lock);
1617 bpage = STAILQ_FIRST(&bz->bounce_page_list);
1619 panic("add_bounce_page: free page list is empty");
1621 STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1622 bz->reserved_bpages--;
1623 bz->active_bpages++;
1624 mtx_unlock(&bounce_lock);
1626 if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1627 /* Page offset needs to be preserved. */
1628 bpage->vaddr |= addr & PAGE_MASK;
1629 bpage->busaddr |= addr & PAGE_MASK;
1631 bpage->datavaddr = vaddr;
1632 bpage->datapage = PHYS_TO_VM_PAGE(addr);
1633 bpage->dataoffs = addr & PAGE_MASK;
1634 bpage->datacount = size;
1635 STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1636 return (bpage->busaddr);
1640 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1642 struct bus_dmamap *map;
1643 struct bounce_zone *bz;
1645 bz = dmat->bounce_zone;
1646 bpage->datavaddr = 0;
1647 bpage->datacount = 0;
1648 if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1650 * Reset the bounce page to start at offset 0. Other uses
1651 * of this bounce page may need to store a full page of
1652 * data and/or assume it starts on a page boundary.
1654 bpage->vaddr &= ~PAGE_MASK;
1655 bpage->busaddr &= ~PAGE_MASK;
1658 mtx_lock(&bounce_lock);
1659 STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1661 bz->active_bpages--;
1662 if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1663 if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1664 STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1665 STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1667 busdma_swi_pending = 1;
1668 bz->total_deferred++;
1669 swi_sched(vm_ih, 0);
1672 mtx_unlock(&bounce_lock);
1679 struct bus_dmamap *map;
1681 mtx_lock(&bounce_lock);
1682 while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1683 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1684 mtx_unlock(&bounce_lock);
1686 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_LOCK);
1687 bus_dmamap_load_mem(map->dmat, map, &map->mem, map->callback,
1688 map->callback_arg, BUS_DMA_WAITOK);
1689 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_UNLOCK);
1690 mtx_lock(&bounce_lock);
1692 mtx_unlock(&bounce_lock);