2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2012-2015 Ian Lepore
5 * Copyright (c) 2010 Mark Tinguely
6 * Copyright (c) 2004 Olivier Houchard
7 * Copyright (c) 2002 Peter Grehan
8 * Copyright (c) 1997, 1998 Justin T. Gibbs.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions, and the following disclaimer,
16 * without modification, immediately at the beginning of the file.
17 * 2. The name of the author may not be used to endorse or promote products
18 * derived from this software without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
24 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * From i386/busdma_machdep.c 191438 2009-04-23 20:24:19Z jhb
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/malloc.h>
42 #include <sys/busdma_bufalloc.h>
43 #include <sys/counter.h>
44 #include <sys/interrupt.h>
45 #include <sys/kernel.h>
48 #include <sys/memdesc.h>
50 #include <sys/mutex.h>
51 #include <sys/sysctl.h>
55 #include <vm/vm_page.h>
56 #include <vm/vm_map.h>
57 #include <vm/vm_extern.h>
58 #include <vm/vm_kern.h>
60 #include <machine/atomic.h>
61 #include <machine/bus.h>
62 #include <machine/cpu.h>
63 #include <machine/md_var.h>
65 #define BUSDMA_DCACHE_ALIGN cpuinfo.dcache_line_size
66 #define BUSDMA_DCACHE_MASK cpuinfo.dcache_line_mask
69 #define MAX_DMA_SEGMENTS 4096
70 #define BUS_DMA_EXCL_BOUNCE BUS_DMA_BUS2
71 #define BUS_DMA_ALIGN_BOUNCE BUS_DMA_BUS3
72 #define BUS_DMA_COULD_BOUNCE (BUS_DMA_EXCL_BOUNCE | BUS_DMA_ALIGN_BOUNCE)
73 #define BUS_DMA_MIN_ALLOC_COMP BUS_DMA_BUS4
83 bus_dma_filter_t *filter;
91 bus_dma_lock_t *lockfunc;
93 struct bounce_zone *bounce_zone;
97 vm_offset_t vaddr; /* kva of bounce buffer */
98 bus_addr_t busaddr; /* Physical address */
99 vm_offset_t datavaddr; /* kva of client data */
100 vm_page_t datapage; /* physical page of client data */
101 vm_offset_t dataoffs; /* page offset of client data */
102 bus_size_t datacount; /* client data count */
103 STAILQ_ENTRY(bounce_page) links;
107 vm_offset_t vaddr; /* kva of client data */
108 bus_addr_t paddr; /* physical address */
109 vm_page_t pages; /* starting page of client data */
110 bus_size_t datacount; /* client data count */
113 int busdma_swi_pending;
116 STAILQ_ENTRY(bounce_zone) links;
117 STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
125 bus_size_t alignment;
129 struct sysctl_ctx_list sysctl_tree;
130 struct sysctl_oid *sysctl_tree_top;
133 static struct mtx bounce_lock;
134 static int total_bpages;
135 static int busdma_zonecount;
136 static uint32_t tags_total;
137 static uint32_t maps_total;
138 static uint32_t maps_dmamem;
139 static uint32_t maps_coherent;
140 static counter_u64_t maploads_total;
141 static counter_u64_t maploads_bounced;
142 static counter_u64_t maploads_coherent;
143 static counter_u64_t maploads_dmamem;
144 static counter_u64_t maploads_mbuf;
145 static counter_u64_t maploads_physmem;
147 static STAILQ_HEAD(, bounce_zone) bounce_zone_list;
149 SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
150 SYSCTL_UINT(_hw_busdma, OID_AUTO, tags_total, CTLFLAG_RD, &tags_total, 0,
151 "Number of active tags");
152 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_total, CTLFLAG_RD, &maps_total, 0,
153 "Number of active maps");
154 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_dmamem, CTLFLAG_RD, &maps_dmamem, 0,
155 "Number of active maps for bus_dmamem_alloc buffers");
156 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_coherent, CTLFLAG_RD, &maps_coherent, 0,
157 "Number of active maps with BUS_DMA_COHERENT flag set");
158 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_total, CTLFLAG_RD,
159 &maploads_total, "Number of load operations performed");
160 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_bounced, CTLFLAG_RD,
161 &maploads_bounced, "Number of load operations that used bounce buffers");
162 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_coherent, CTLFLAG_RD,
163 &maploads_dmamem, "Number of load operations on BUS_DMA_COHERENT memory");
164 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_dmamem, CTLFLAG_RD,
165 &maploads_dmamem, "Number of load operations on bus_dmamem_alloc buffers");
166 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_mbuf, CTLFLAG_RD,
167 &maploads_mbuf, "Number of load operations for mbufs");
168 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_physmem, CTLFLAG_RD,
169 &maploads_physmem, "Number of load operations on physical buffers");
170 SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bpages, 0,
171 "Total bounce pages");
174 struct bp_list bpages;
179 bus_dmamap_callback_t *callback;
182 #define DMAMAP_COHERENT (1 << 0)
183 #define DMAMAP_DMAMEM_ALLOC (1 << 1)
184 #define DMAMAP_MBUF (1 << 2)
185 STAILQ_ENTRY(bus_dmamap) links;
186 bus_dma_segment_t *segments;
188 struct sync_list slist[];
191 static STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
192 static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist;
194 static void init_bounce_pages(void *dummy);
195 static int alloc_bounce_zone(bus_dma_tag_t dmat);
196 static int alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages);
197 static int reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
199 static bus_addr_t add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map,
200 vm_offset_t vaddr, bus_addr_t addr, bus_size_t size);
201 static void free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage);
202 static void _bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap,
203 bus_dmamap_t map, void *buf, bus_size_t buflen, int flags);
204 static void _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map,
205 vm_paddr_t buf, bus_size_t buflen, int flags);
206 static int _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
208 static void dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size);
209 static void dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op);
211 static busdma_bufalloc_t coherent_allocator; /* Cache of coherent buffers */
212 static busdma_bufalloc_t standard_allocator; /* Cache of standard buffers */
214 MALLOC_DEFINE(M_BUSDMA, "busdma", "busdma metadata");
215 MALLOC_DEFINE(M_BOUNCE, "bounce", "busdma bounce pages");
218 busdma_init(void *dummy)
222 maploads_total = counter_u64_alloc(M_WAITOK);
223 maploads_bounced = counter_u64_alloc(M_WAITOK);
224 maploads_coherent = counter_u64_alloc(M_WAITOK);
225 maploads_dmamem = counter_u64_alloc(M_WAITOK);
226 maploads_mbuf = counter_u64_alloc(M_WAITOK);
227 maploads_physmem = counter_u64_alloc(M_WAITOK);
231 /* Create a cache of buffers in standard (cacheable) memory. */
232 standard_allocator = busdma_bufalloc_create("buffer",
233 BUSDMA_DCACHE_ALIGN,/* minimum_alignment */
234 NULL, /* uma_alloc func */
235 NULL, /* uma_free func */
236 uma_flags); /* uma_zcreate_flags */
240 * Force UMA zone to allocate service structures like
241 * slabs using own allocator. uma_debug code performs
242 * atomic ops on uma_slab_t fields and safety of this
243 * operation is not guaranteed for write-back caches
245 uma_flags = UMA_ZONE_OFFPAGE;
248 * Create a cache of buffers in uncacheable memory, to implement the
249 * BUS_DMA_COHERENT (and potentially BUS_DMA_NOCACHE) flag.
251 coherent_allocator = busdma_bufalloc_create("coherent",
252 BUSDMA_DCACHE_ALIGN,/* minimum_alignment */
253 busdma_bufalloc_alloc_uncacheable,
254 busdma_bufalloc_free_uncacheable,
255 uma_flags); /* uma_zcreate_flags */
259 * This init historically used SI_SUB_VM, but now the init code requires
260 * malloc(9) using M_BUSDMA memory and the pcpu zones for counter(9), which get
261 * set up by SI_SUB_KMEM and SI_ORDER_LAST, so we'll go right after that by
262 * using SI_SUB_KMEM+1.
264 SYSINIT(busdma, SI_SUB_KMEM+1, SI_ORDER_FIRST, busdma_init, NULL);
267 * This routine checks the exclusion zone constraints from a tag against the
268 * physical RAM available on the machine. If a tag specifies an exclusion zone
269 * but there's no RAM in that zone, then we avoid allocating resources to bounce
270 * a request, and we can use any memory allocator (as opposed to needing
271 * kmem_alloc_contig() just because it can allocate pages in an address range).
273 * Most tags have BUS_SPACE_MAXADDR or BUS_SPACE_MAXADDR_32BIT (they are the
274 * same value on 32-bit architectures) as their lowaddr constraint, and we can't
275 * possibly have RAM at an address higher than the highest address we can
276 * express, so we take a fast out.
279 exclusion_bounce_check(vm_offset_t lowaddr, vm_offset_t highaddr)
283 if (lowaddr >= BUS_SPACE_MAXADDR)
286 for (i = 0; phys_avail[i] && phys_avail[i + 1]; i += 2) {
287 if ((lowaddr >= phys_avail[i] && lowaddr < phys_avail[i + 1]) ||
288 (lowaddr < phys_avail[i] && highaddr >= phys_avail[i]))
295 * Return true if the tag has an exclusion zone that could lead to bouncing.
298 exclusion_bounce(bus_dma_tag_t dmat)
301 return (dmat->flags & BUS_DMA_EXCL_BOUNCE);
305 * Return true if the given address does not fall on the alignment boundary.
308 alignment_bounce(bus_dma_tag_t dmat, bus_addr_t addr)
311 return (addr & (dmat->alignment - 1));
315 * Return true if the DMA should bounce because the start or end does not fall
316 * on a cacheline boundary (which would require a partial cacheline flush).
317 * COHERENT memory doesn't trigger cacheline flushes. Memory allocated by
318 * bus_dmamem_alloc() is always aligned to cacheline boundaries, and there's a
319 * strict rule that such memory cannot be accessed by the CPU while DMA is in
320 * progress (or by multiple DMA engines at once), so that it's always safe to do
321 * full cacheline flushes even if that affects memory outside the range of a
322 * given DMA operation that doesn't involve the full allocated buffer. If we're
323 * mapping an mbuf, that follows the same rules as a buffer we allocated.
326 cacheline_bounce(bus_dmamap_t map, bus_addr_t addr, bus_size_t size)
329 if (map->flags & (DMAMAP_DMAMEM_ALLOC | DMAMAP_COHERENT | DMAMAP_MBUF))
331 return ((addr | size) & BUSDMA_DCACHE_MASK);
335 * Return true if we might need to bounce the DMA described by addr and size.
337 * This is used to quick-check whether we need to do the more expensive work of
338 * checking the DMA page-by-page looking for alignment and exclusion bounces.
340 * Note that the addr argument might be either virtual or physical. It doesn't
341 * matter because we only look at the low-order bits, which are the same in both
345 might_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t addr,
349 return ((dmat->flags & BUS_DMA_EXCL_BOUNCE) ||
350 alignment_bounce(dmat, addr) ||
351 cacheline_bounce(map, addr, size));
355 * Return true if we must bounce the DMA described by paddr and size.
357 * Bouncing can be triggered by DMA that doesn't begin and end on cacheline
358 * boundaries, or doesn't begin on an alignment boundary, or falls within the
359 * exclusion zone of any tag in the ancestry chain.
361 * For exclusions, walk the chain of tags comparing paddr to the exclusion zone
362 * within each tag. If the tag has a filter function, use it to decide whether
363 * the DMA needs to bounce, otherwise any DMA within the zone bounces.
366 must_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t paddr,
370 if (cacheline_bounce(map, paddr, size))
374 * The tag already contains ancestors' alignment restrictions so this
375 * check doesn't need to be inside the loop.
377 if (alignment_bounce(dmat, paddr))
381 * Even though each tag has an exclusion zone that is a superset of its
382 * own and all its ancestors' exclusions, the exclusion zone of each tag
383 * up the chain must be checked within the loop, because the busdma
384 * rules say the filter function is called only when the address lies
385 * within the low-highaddr range of the tag that filterfunc belongs to.
387 while (dmat != NULL && exclusion_bounce(dmat)) {
388 if ((paddr >= dmat->lowaddr && paddr <= dmat->highaddr) &&
389 (dmat->filter == NULL ||
390 dmat->filter(dmat->filterarg, paddr) != 0))
399 * Convenience function for manipulating driver locks from busdma (during
400 * busdma_swi, for example). Drivers that don't provide their own locks
401 * should specify &Giant to dmat->lockfuncarg. Drivers that use their own
402 * non-mutex locking scheme don't have to use this at all.
405 busdma_lock_mutex(void *arg, bus_dma_lock_op_t op)
409 dmtx = (struct mtx *)arg;
418 panic("Unknown operation 0x%x for busdma_lock_mutex!", op);
423 * dflt_lock should never get called. It gets put into the dma tag when
424 * lockfunc == NULL, which is only valid if the maps that are associated
425 * with the tag are meant to never be defered.
426 * XXX Should have a way to identify which driver is responsible here.
429 dflt_lock(void *arg, bus_dma_lock_op_t op)
432 panic("driver error: busdma dflt_lock called");
436 * Allocate a device specific dma_tag.
439 bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
440 bus_addr_t boundary, bus_addr_t lowaddr, bus_addr_t highaddr,
441 bus_dma_filter_t *filter, void *filterarg, bus_size_t maxsize,
442 int nsegments, bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
443 void *lockfuncarg, bus_dma_tag_t *dmat)
445 bus_dma_tag_t newtag;
448 /* Basic sanity checking. */
449 KASSERT(boundary == 0 || powerof2(boundary),
450 ("dma tag boundary %lu, must be a power of 2", boundary));
451 KASSERT(boundary == 0 || boundary >= maxsegsz,
452 ("dma tag boundary %lu is < maxsegsz %lu\n", boundary, maxsegsz));
453 KASSERT(alignment != 0 && powerof2(alignment),
454 ("dma tag alignment %lu, must be non-zero power of 2", alignment));
455 KASSERT(maxsegsz != 0, ("dma tag maxsegsz must not be zero"));
457 /* Return a NULL tag on failure */
460 newtag = (bus_dma_tag_t)malloc(sizeof(*newtag), M_BUSDMA,
462 if (newtag == NULL) {
463 CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
464 __func__, newtag, 0, error);
468 newtag->parent = parent;
469 newtag->alignment = alignment;
470 newtag->boundary = boundary;
471 newtag->lowaddr = trunc_page((vm_paddr_t)lowaddr) + (PAGE_SIZE - 1);
472 newtag->highaddr = trunc_page((vm_paddr_t)highaddr) +
474 newtag->filter = filter;
475 newtag->filterarg = filterarg;
476 newtag->maxsize = maxsize;
477 newtag->nsegments = nsegments;
478 newtag->maxsegsz = maxsegsz;
479 newtag->flags = flags;
480 newtag->ref_count = 1; /* Count ourself */
481 newtag->map_count = 0;
482 if (lockfunc != NULL) {
483 newtag->lockfunc = lockfunc;
484 newtag->lockfuncarg = lockfuncarg;
486 newtag->lockfunc = dflt_lock;
487 newtag->lockfuncarg = NULL;
490 /* Take into account any restrictions imposed by our parent tag */
491 if (parent != NULL) {
492 newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
493 newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
494 newtag->alignment = MAX(parent->alignment, newtag->alignment);
495 newtag->flags |= parent->flags & BUS_DMA_COULD_BOUNCE;
496 newtag->flags |= parent->flags & BUS_DMA_COHERENT;
497 if (newtag->boundary == 0)
498 newtag->boundary = parent->boundary;
499 else if (parent->boundary != 0)
500 newtag->boundary = MIN(parent->boundary,
502 if (newtag->filter == NULL) {
504 * Short circuit to looking at our parent directly
505 * since we have encapsulated all of its information
507 newtag->filter = parent->filter;
508 newtag->filterarg = parent->filterarg;
509 newtag->parent = parent->parent;
511 if (newtag->parent != NULL)
512 atomic_add_int(&parent->ref_count, 1);
515 if (exclusion_bounce_check(newtag->lowaddr, newtag->highaddr))
516 newtag->flags |= BUS_DMA_EXCL_BOUNCE;
517 if (alignment_bounce(newtag, 1))
518 newtag->flags |= BUS_DMA_ALIGN_BOUNCE;
521 * Any request can auto-bounce due to cacheline alignment, in addition
522 * to any alignment or boundary specifications in the tag, so if the
523 * ALLOCNOW flag is set, there's always work to do.
525 if ((flags & BUS_DMA_ALLOCNOW) != 0) {
526 struct bounce_zone *bz;
528 * Round size up to a full page, and add one more page because
529 * there can always be one more boundary crossing than the
530 * number of pages in a transfer.
532 maxsize = roundup2(maxsize, PAGE_SIZE) + PAGE_SIZE;
534 if ((error = alloc_bounce_zone(newtag)) != 0) {
535 free(newtag, M_BUSDMA);
538 bz = newtag->bounce_zone;
540 if (ptoa(bz->total_bpages) < maxsize) {
543 pages = atop(maxsize) - bz->total_bpages;
545 /* Add pages to our bounce pool */
546 if (alloc_bounce_pages(newtag, pages) < pages)
549 /* Performed initial allocation */
550 newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
552 newtag->bounce_zone = NULL;
555 free(newtag, M_BUSDMA);
557 atomic_add_32(&tags_total, 1);
560 CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
561 __func__, newtag, (newtag != NULL ? newtag->flags : 0), error);
566 bus_dma_tag_destroy(bus_dma_tag_t dmat)
568 bus_dma_tag_t dmat_copy;
576 if (dmat->map_count != 0) {
581 while (dmat != NULL) {
582 bus_dma_tag_t parent;
584 parent = dmat->parent;
585 atomic_subtract_int(&dmat->ref_count, 1);
586 if (dmat->ref_count == 0) {
587 atomic_subtract_32(&tags_total, 1);
588 free(dmat, M_BUSDMA);
590 * Last reference count, so
591 * release our reference
592 * count on our parent.
600 CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
605 allocate_bz_and_pages(bus_dma_tag_t dmat, bus_dmamap_t mapp)
607 struct bounce_zone *bz;
611 if (dmat->bounce_zone == NULL)
612 if ((error = alloc_bounce_zone(dmat)) != 0)
614 bz = dmat->bounce_zone;
615 /* Initialize the new map */
616 STAILQ_INIT(&(mapp->bpages));
619 * Attempt to add pages to our pool on a per-instance basis up to a sane
620 * limit. Even if the tag isn't flagged as COULD_BOUNCE due to
621 * alignment and boundary constraints, it could still auto-bounce due to
622 * cacheline alignment, which requires at most two bounce pages.
624 if (dmat->flags & BUS_DMA_COULD_BOUNCE)
625 maxpages = MAX_BPAGES;
627 maxpages = 2 * bz->map_count;
628 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0 ||
629 (bz->map_count > 0 && bz->total_bpages < maxpages)) {
632 pages = atop(roundup2(dmat->maxsize, PAGE_SIZE)) + 1;
633 pages = MIN(maxpages - bz->total_bpages, pages);
634 pages = MAX(pages, 2);
635 if (alloc_bounce_pages(dmat, pages) < pages)
638 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0)
639 dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
646 allocate_map(bus_dma_tag_t dmat, int mflags)
648 int mapsize, segsize;
652 * Allocate the map. The map structure ends with an embedded
653 * variable-sized array of sync_list structures. Following that
654 * we allocate enough extra space to hold the array of bus_dma_segments.
656 KASSERT(dmat->nsegments <= MAX_DMA_SEGMENTS,
657 ("cannot allocate %u dma segments (max is %u)",
658 dmat->nsegments, MAX_DMA_SEGMENTS));
659 segsize = sizeof(struct bus_dma_segment) * dmat->nsegments;
660 mapsize = sizeof(*map) + sizeof(struct sync_list) * dmat->nsegments;
661 map = malloc(mapsize + segsize, M_BUSDMA, mflags | M_ZERO);
663 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
666 map->segments = (bus_dma_segment_t *)((uintptr_t)map + mapsize);
671 * Allocate a handle for mapping from kva/uva/physical
672 * address space into bus device space.
675 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
680 *mapp = map = allocate_map(dmat, M_NOWAIT);
682 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
687 * Bouncing might be required if the driver asks for an exclusion
688 * region, a data alignment that is stricter than 1, or DMA that begins
689 * or ends with a partial cacheline. Whether bouncing will actually
690 * happen can't be known until mapping time, but we need to pre-allocate
691 * resources now because we might not be allowed to at mapping time.
693 error = allocate_bz_and_pages(dmat, map);
699 if (map->flags & DMAMAP_COHERENT)
700 atomic_add_32(&maps_coherent, 1);
701 atomic_add_32(&maps_total, 1);
708 * Destroy a handle for mapping from kva/uva/physical
709 * address space into bus device space.
712 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
715 if (STAILQ_FIRST(&map->bpages) != NULL || map->sync_count != 0) {
716 CTR3(KTR_BUSDMA, "%s: tag %p error %d",
717 __func__, dmat, EBUSY);
720 if (dmat->bounce_zone)
721 dmat->bounce_zone->map_count--;
722 if (map->flags & DMAMAP_COHERENT)
723 atomic_subtract_32(&maps_coherent, 1);
724 atomic_subtract_32(&maps_total, 1);
727 CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
732 * Allocate a piece of memory that can be efficiently mapped into bus device
733 * space based on the constraints listed in the dma tag. Returns a pointer to
734 * the allocated memory, and a pointer to an associated bus_dmamap.
737 bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
740 busdma_bufalloc_t ba;
741 struct busdma_bufzone *bufzone;
743 vm_memattr_t memattr;
746 if (flags & BUS_DMA_NOWAIT)
750 if (flags & BUS_DMA_ZERO)
753 *mapp = map = allocate_map(dmat, mflags);
755 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
756 __func__, dmat, dmat->flags, ENOMEM);
759 map->flags = DMAMAP_DMAMEM_ALLOC;
761 /* For coherent memory, set the map flag that disables sync ops. */
762 if (flags & BUS_DMA_COHERENT)
763 map->flags |= DMAMAP_COHERENT;
766 * Choose a busdma buffer allocator based on memory type flags.
767 * If the tag's COHERENT flag is set, that means normal memory
768 * is already coherent, use the normal allocator.
770 if ((flags & BUS_DMA_COHERENT) &&
771 ((dmat->flags & BUS_DMA_COHERENT) == 0)) {
772 memattr = VM_MEMATTR_UNCACHEABLE;
773 ba = coherent_allocator;
775 memattr = VM_MEMATTR_DEFAULT;
776 ba = standard_allocator;
780 * Try to find a bufzone in the allocator that holds a cache of buffers
781 * of the right size for this request. If the buffer is too big to be
782 * held in the allocator cache, this returns NULL.
784 bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
787 * Allocate the buffer from the uma(9) allocator if...
788 * - It's small enough to be in the allocator (bufzone not NULL).
789 * - The alignment constraint isn't larger than the allocation size
790 * (the allocator aligns buffers to their size boundaries).
791 * - There's no need to handle lowaddr/highaddr exclusion zones.
792 * else allocate non-contiguous pages if...
793 * - The page count that could get allocated doesn't exceed
794 * nsegments also when the maximum segment size is less
796 * - The alignment constraint isn't larger than a page boundary.
797 * - There are no boundary-crossing constraints.
798 * else allocate a block of contiguous pages because one or more of the
799 * constraints is something that only the contig allocator can fulfill.
801 if (bufzone != NULL && dmat->alignment <= bufzone->size &&
802 !exclusion_bounce(dmat)) {
803 *vaddr = uma_zalloc(bufzone->umazone, mflags);
804 } else if (dmat->nsegments >=
805 howmany(dmat->maxsize, MIN(dmat->maxsegsz, PAGE_SIZE)) &&
806 dmat->alignment <= PAGE_SIZE &&
807 (dmat->boundary % PAGE_SIZE) == 0) {
808 *vaddr = (void *)kmem_alloc_attr(kernel_arena, dmat->maxsize,
809 mflags, 0, dmat->lowaddr, memattr);
811 *vaddr = (void *)kmem_alloc_contig(kernel_arena, dmat->maxsize,
812 mflags, 0, dmat->lowaddr, dmat->alignment, dmat->boundary,
815 if (*vaddr == NULL) {
816 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
817 __func__, dmat, dmat->flags, ENOMEM);
822 if (map->flags & DMAMAP_COHERENT)
823 atomic_add_32(&maps_coherent, 1);
824 atomic_add_32(&maps_dmamem, 1);
825 atomic_add_32(&maps_total, 1);
828 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
829 __func__, dmat, dmat->flags, 0);
834 * Free a piece of memory that was allocated via bus_dmamem_alloc, along with
835 * its associated map.
838 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
840 struct busdma_bufzone *bufzone;
841 busdma_bufalloc_t ba;
843 if ((map->flags & DMAMAP_COHERENT) &&
844 ((dmat->flags & BUS_DMA_COHERENT) == 0))
845 ba = coherent_allocator;
847 ba = standard_allocator;
849 bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
851 if (bufzone != NULL && dmat->alignment <= bufzone->size &&
852 !exclusion_bounce(dmat))
853 uma_zfree(bufzone->umazone, vaddr);
855 kmem_free(kernel_arena, (vm_offset_t)vaddr, dmat->maxsize);
858 if (map->flags & DMAMAP_COHERENT)
859 atomic_subtract_32(&maps_coherent, 1);
860 atomic_subtract_32(&maps_total, 1);
861 atomic_subtract_32(&maps_dmamem, 1);
863 CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat, dmat->flags);
867 _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
868 bus_size_t buflen, int flags)
873 if (map->pagesneeded == 0) {
874 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
875 " map= %p, pagesneeded= %d",
876 dmat->lowaddr, dmat->boundary, dmat->alignment,
877 map, map->pagesneeded);
879 * Count the number of bounce pages
880 * needed in order to complete this transfer
883 while (buflen != 0) {
884 sgsize = MIN(buflen, dmat->maxsegsz);
885 if (must_bounce(dmat, map, curaddr, sgsize) != 0) {
887 PAGE_SIZE - (curaddr & PAGE_MASK));
893 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
898 _bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap, bus_dmamap_t map,
899 void *buf, bus_size_t buflen, int flags)
902 vm_offset_t vendaddr;
905 if (map->pagesneeded == 0) {
906 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
907 " map= %p, pagesneeded= %d",
908 dmat->lowaddr, dmat->boundary, dmat->alignment,
909 map, map->pagesneeded);
911 * Count the number of bounce pages
912 * needed in order to complete this transfer
914 vaddr = (vm_offset_t)buf;
915 vendaddr = (vm_offset_t)buf + buflen;
917 while (vaddr < vendaddr) {
918 if (__predict_true(pmap == kernel_pmap))
919 paddr = pmap_kextract(vaddr);
921 paddr = pmap_extract(pmap, vaddr);
922 if (must_bounce(dmat, map, paddr,
923 min(vendaddr - vaddr, (PAGE_SIZE - ((vm_offset_t)vaddr &
924 PAGE_MASK)))) != 0) {
927 vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
930 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
935 _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int flags)
938 /* Reserve Necessary Bounce Pages */
939 mtx_lock(&bounce_lock);
940 if (flags & BUS_DMA_NOWAIT) {
941 if (reserve_bounce_pages(dmat, map, 0) != 0) {
942 map->pagesneeded = 0;
943 mtx_unlock(&bounce_lock);
947 if (reserve_bounce_pages(dmat, map, 1) != 0) {
948 /* Queue us for resources */
949 STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
950 mtx_unlock(&bounce_lock);
951 return (EINPROGRESS);
954 mtx_unlock(&bounce_lock);
960 * Add a single contiguous physical range to the segment list.
963 _bus_dmamap_addseg(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t curaddr,
964 bus_size_t sgsize, bus_dma_segment_t *segs, int *segp)
966 bus_addr_t baddr, bmask;
970 * Make sure we don't cross any boundaries.
972 bmask = ~(dmat->boundary - 1);
973 if (dmat->boundary > 0) {
974 baddr = (curaddr + dmat->boundary) & bmask;
975 if (sgsize > (baddr - curaddr))
976 sgsize = (baddr - curaddr);
980 * Insert chunk into a segment, coalescing with
981 * previous segment if possible.
986 segs[seg].ds_addr = curaddr;
987 segs[seg].ds_len = sgsize;
989 if (curaddr == segs[seg].ds_addr + segs[seg].ds_len &&
990 (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
991 (dmat->boundary == 0 ||
992 (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
993 segs[seg].ds_len += sgsize;
995 if (++seg >= dmat->nsegments)
997 segs[seg].ds_addr = curaddr;
998 segs[seg].ds_len = sgsize;
1006 * Utility function to load a physical buffer. segp contains
1007 * the starting segment on entrace, and the ending segment on exit.
1010 _bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
1011 bus_size_t buflen, int flags, bus_dma_segment_t *segs, int *segp)
1014 bus_addr_t sl_end = 0;
1016 struct sync_list *sl;
1020 segs = map->segments;
1022 counter_u64_add(maploads_total, 1);
1023 counter_u64_add(maploads_physmem, 1);
1025 if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1026 _bus_dmamap_count_phys(dmat, map, buf, buflen, flags);
1027 if (map->pagesneeded != 0) {
1028 counter_u64_add(maploads_bounced, 1);
1029 error = _bus_dmamap_reserve_pages(dmat, map, flags);
1035 sl = map->slist + map->sync_count - 1;
1037 while (buflen > 0) {
1039 sgsize = MIN(buflen, dmat->maxsegsz);
1040 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1042 sgsize = MIN(sgsize, PAGE_SIZE - (curaddr & PAGE_MASK));
1043 curaddr = add_bounce_page(dmat, map, 0, curaddr,
1045 } else if ((dmat->flags & BUS_DMA_COHERENT) == 0) {
1046 if (map->sync_count > 0)
1047 sl_end = sl->paddr + sl->datacount;
1049 if (map->sync_count == 0 || curaddr != sl_end) {
1050 if (++map->sync_count > dmat->nsegments)
1054 sl->paddr = curaddr;
1055 sl->datacount = sgsize;
1056 sl->pages = PHYS_TO_VM_PAGE(curaddr);
1057 KASSERT(sl->pages != NULL,
1058 ("%s: page at PA:0x%08lx is not in "
1059 "vm_page_array", __func__, curaddr));
1061 sl->datacount += sgsize;
1063 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1075 bus_dmamap_unload(dmat, map);
1076 return (EFBIG); /* XXX better return value here? */
1082 _bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map,
1083 struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
1084 bus_dma_segment_t *segs, int *segp)
1087 return (bus_dmamap_load_ma_triv(dmat, map, ma, tlen, ma_offs, flags,
1092 * Utility function to load a linear buffer. segp contains
1093 * the starting segment on entrance, and the ending segment on exit.
1096 _bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
1097 bus_size_t buflen, pmap_t pmap, int flags, bus_dma_segment_t *segs,
1102 bus_addr_t sl_pend = 0;
1103 vm_offset_t kvaddr, vaddr, sl_vend = 0;
1104 struct sync_list *sl;
1107 counter_u64_add(maploads_total, 1);
1108 if (map->flags & DMAMAP_COHERENT)
1109 counter_u64_add(maploads_coherent, 1);
1110 if (map->flags & DMAMAP_DMAMEM_ALLOC)
1111 counter_u64_add(maploads_dmamem, 1);
1114 segs = map->segments;
1116 if (flags & BUS_DMA_LOAD_MBUF) {
1117 counter_u64_add(maploads_mbuf, 1);
1118 map->flags |= DMAMAP_MBUF;
1121 if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1122 _bus_dmamap_count_pages(dmat, pmap, map, buf, buflen, flags);
1123 if (map->pagesneeded != 0) {
1124 counter_u64_add(maploads_bounced, 1);
1125 error = _bus_dmamap_reserve_pages(dmat, map, flags);
1131 sl = map->slist + map->sync_count - 1;
1132 vaddr = (vm_offset_t)buf;
1134 while (buflen > 0) {
1136 * Get the physical address for this segment.
1138 if (__predict_true(pmap == kernel_pmap)) {
1139 curaddr = pmap_kextract(vaddr);
1142 curaddr = pmap_extract(pmap, vaddr);
1147 * Compute the segment size, and adjust counts.
1149 sgsize = PAGE_SIZE - (curaddr & PAGE_MASK);
1150 if (sgsize > dmat->maxsegsz)
1151 sgsize = dmat->maxsegsz;
1152 if (buflen < sgsize)
1155 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1157 curaddr = add_bounce_page(dmat, map, kvaddr, curaddr,
1159 } else if ((dmat->flags & BUS_DMA_COHERENT) == 0) {
1160 if (map->sync_count > 0) {
1161 sl_pend = sl->paddr + sl->datacount;
1162 sl_vend = sl->vaddr + sl->datacount;
1165 if (map->sync_count == 0 ||
1166 (kvaddr != 0 && kvaddr != sl_vend) ||
1167 (curaddr != sl_pend)) {
1169 if (++map->sync_count > dmat->nsegments)
1173 sl->paddr = curaddr;
1177 sl->pages = PHYS_TO_VM_PAGE(curaddr);
1178 KASSERT(sl->pages != NULL,
1179 ("%s: page at PA:0x%08lx is not "
1180 "in vm_page_array", __func__,
1183 sl->datacount = sgsize;
1185 sl->datacount += sgsize;
1187 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1200 bus_dmamap_unload(dmat, map);
1201 return (EFBIG); /* XXX better return value here? */
1207 _bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map, struct memdesc *mem,
1208 bus_dmamap_callback_t *callback, void *callback_arg)
1213 map->callback = callback;
1214 map->callback_arg = callback_arg;
1218 _bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map,
1219 bus_dma_segment_t *segs, int nsegs, int error)
1223 segs = map->segments;
1228 * Release the mapping held by map.
1231 bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1233 struct bounce_page *bpage;
1234 struct bounce_zone *bz;
1236 if ((bz = dmat->bounce_zone) != NULL) {
1237 while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1238 STAILQ_REMOVE_HEAD(&map->bpages, links);
1239 free_bounce_page(dmat, bpage);
1242 bz = dmat->bounce_zone;
1243 bz->free_bpages += map->pagesreserved;
1244 bz->reserved_bpages -= map->pagesreserved;
1245 map->pagesreserved = 0;
1246 map->pagesneeded = 0;
1248 map->sync_count = 0;
1249 map->flags &= ~DMAMAP_MBUF;
1253 dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size)
1256 * Write back any partial cachelines immediately before and
1257 * after the DMA region. We don't need to round the address
1258 * down to the nearest cacheline or specify the exact size,
1259 * as dcache_wb_poc() will do the rounding for us and works
1260 * at cacheline granularity.
1262 if (va & BUSDMA_DCACHE_MASK)
1263 dcache_wb_poc(va, pa, 1);
1264 if ((va + size) & BUSDMA_DCACHE_MASK)
1265 dcache_wb_poc(va + size, pa + size, 1);
1267 dcache_inv_poc_dma(va, pa, size);
1271 dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op)
1273 uint32_t len, offset;
1276 vm_offset_t va, tempva;
1279 offset = sl->paddr & PAGE_MASK;
1281 size = sl->datacount;
1284 for ( ; size != 0; size -= len, pa += len, offset = 0, ++m) {
1286 if (sl->vaddr == 0) {
1287 len = min(PAGE_SIZE - offset, size);
1288 tempva = pmap_quick_enter_page(m);
1289 va = tempva | offset;
1290 KASSERT(pa == (VM_PAGE_TO_PHYS(m) | offset),
1291 ("unexpected vm_page_t phys: 0x%08x != 0x%08x",
1292 VM_PAGE_TO_PHYS(m) | offset, pa));
1294 len = sl->datacount;
1299 case BUS_DMASYNC_PREWRITE:
1300 case BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD:
1301 dcache_wb_poc(va, pa, len);
1303 case BUS_DMASYNC_PREREAD:
1305 * An mbuf may start in the middle of a cacheline. There
1306 * will be no cpu writes to the beginning of that line
1307 * (which contains the mbuf header) while dma is in
1308 * progress. Handle that case by doing a writeback of
1309 * just the first cacheline before invalidating the
1310 * overall buffer. Any mbuf in a chain may have this
1311 * misalignment. Buffers which are not mbufs bounce if
1312 * they are not aligned to a cacheline.
1314 dma_preread_safe(va, pa, len);
1316 case BUS_DMASYNC_POSTREAD:
1317 case BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE:
1318 dcache_inv_poc(va, pa, len);
1321 panic("unsupported combination of sync operations: "
1326 pmap_quick_remove_page(tempva);
1331 bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1333 struct bounce_page *bpage;
1334 struct sync_list *sl, *end;
1335 vm_offset_t datavaddr, tempvaddr;
1337 if (op == BUS_DMASYNC_POSTWRITE)
1341 * If the buffer was from user space, it is possible that this is not
1342 * the same vm map, especially on a POST operation. It's not clear that
1343 * dma on userland buffers can work at all right now. To be safe, until
1344 * we're able to test direct userland dma, panic on a map mismatch.
1346 if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1348 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1349 "performing bounce", __func__, dmat, dmat->flags, op);
1352 * For PREWRITE do a writeback. Clean the caches from the
1353 * innermost to the outermost levels.
1355 if (op & BUS_DMASYNC_PREWRITE) {
1356 while (bpage != NULL) {
1358 datavaddr = bpage->datavaddr;
1359 if (datavaddr == 0) {
1360 tempvaddr = pmap_quick_enter_page(
1362 datavaddr = tempvaddr | bpage->dataoffs;
1364 bcopy((void *)datavaddr, (void *)bpage->vaddr,
1367 pmap_quick_remove_page(tempvaddr);
1368 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1369 dcache_wb_poc(bpage->vaddr,
1370 bpage->busaddr, bpage->datacount);
1371 bpage = STAILQ_NEXT(bpage, links);
1373 dmat->bounce_zone->total_bounced++;
1377 * Do an invalidate for PREREAD unless a writeback was already
1378 * done above due to PREWRITE also being set. The reason for a
1379 * PREREAD invalidate is to prevent dirty lines currently in the
1380 * cache from being evicted during the DMA. If a writeback was
1381 * done due to PREWRITE also being set there will be no dirty
1382 * lines and the POSTREAD invalidate handles the rest. The
1383 * invalidate is done from the innermost to outermost level. If
1384 * L2 were done first, a dirty cacheline could be automatically
1385 * evicted from L1 before we invalidated it, re-dirtying the L2.
1387 if ((op & BUS_DMASYNC_PREREAD) && !(op & BUS_DMASYNC_PREWRITE)) {
1388 bpage = STAILQ_FIRST(&map->bpages);
1389 while (bpage != NULL) {
1390 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1391 dcache_inv_poc_dma(bpage->vaddr,
1392 bpage->busaddr, bpage->datacount);
1393 bpage = STAILQ_NEXT(bpage, links);
1398 * Re-invalidate the caches on a POSTREAD, even though they were
1399 * already invalidated at PREREAD time. Aggressive prefetching
1400 * due to accesses to other data near the dma buffer could have
1401 * brought buffer data into the caches which is now stale. The
1402 * caches are invalidated from the outermost to innermost; the
1403 * prefetches could be happening right now, and if L1 were
1404 * invalidated first, stale L2 data could be prefetched into L1.
1406 if (op & BUS_DMASYNC_POSTREAD) {
1407 while (bpage != NULL) {
1408 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1409 dcache_inv_poc(bpage->vaddr,
1410 bpage->busaddr, bpage->datacount);
1412 datavaddr = bpage->datavaddr;
1413 if (datavaddr == 0) {
1414 tempvaddr = pmap_quick_enter_page(
1416 datavaddr = tempvaddr | bpage->dataoffs;
1418 bcopy((void *)bpage->vaddr, (void *)datavaddr,
1421 pmap_quick_remove_page(tempvaddr);
1422 bpage = STAILQ_NEXT(bpage, links);
1424 dmat->bounce_zone->total_bounced++;
1429 * For COHERENT memory no cache maintenance is necessary, but ensure all
1430 * writes have reached memory for the PREWRITE case. No action is
1431 * needed for a PREREAD without PREWRITE also set, because that would
1432 * imply that the cpu had written to the COHERENT buffer and expected
1433 * the dma device to see that change, and by definition a PREWRITE sync
1434 * is required to make that happen.
1436 if (map->flags & DMAMAP_COHERENT) {
1437 if (op & BUS_DMASYNC_PREWRITE) {
1439 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1440 cpu_l2cache_drain_writebuf();
1446 * Cache maintenance for normal (non-COHERENT non-bounce) buffers. All
1447 * the comments about the sequences for flushing cache levels in the
1448 * bounce buffer code above apply here as well. In particular, the fact
1449 * that the sequence is inner-to-outer for PREREAD invalidation and
1450 * outer-to-inner for POSTREAD invalidation is not a mistake.
1452 if (map->sync_count != 0) {
1453 sl = &map->slist[0];
1454 end = &map->slist[map->sync_count];
1455 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1456 "performing sync", __func__, dmat, dmat->flags, op);
1458 for ( ; sl != end; ++sl)
1459 dma_dcache_sync(sl, op);
1464 init_bounce_pages(void *dummy __unused)
1468 STAILQ_INIT(&bounce_zone_list);
1469 STAILQ_INIT(&bounce_map_waitinglist);
1470 STAILQ_INIT(&bounce_map_callbacklist);
1471 mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
1473 SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
1475 static struct sysctl_ctx_list *
1476 busdma_sysctl_tree(struct bounce_zone *bz)
1479 return (&bz->sysctl_tree);
1482 static struct sysctl_oid *
1483 busdma_sysctl_tree_top(struct bounce_zone *bz)
1486 return (bz->sysctl_tree_top);
1490 alloc_bounce_zone(bus_dma_tag_t dmat)
1492 struct bounce_zone *bz;
1494 /* Check to see if we already have a suitable zone */
1495 STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1496 if ((dmat->alignment <= bz->alignment) &&
1497 (dmat->lowaddr >= bz->lowaddr)) {
1498 dmat->bounce_zone = bz;
1503 if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_BUSDMA,
1504 M_NOWAIT | M_ZERO)) == NULL)
1507 STAILQ_INIT(&bz->bounce_page_list);
1508 bz->free_bpages = 0;
1509 bz->reserved_bpages = 0;
1510 bz->active_bpages = 0;
1511 bz->lowaddr = dmat->lowaddr;
1512 bz->alignment = MAX(dmat->alignment, PAGE_SIZE);
1514 snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1516 snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1517 STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1518 dmat->bounce_zone = bz;
1520 sysctl_ctx_init(&bz->sysctl_tree);
1521 bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
1522 SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1524 if (bz->sysctl_tree_top == NULL) {
1525 sysctl_ctx_free(&bz->sysctl_tree);
1526 return (0); /* XXX error code? */
1529 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1530 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1531 "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1532 "Total bounce pages");
1533 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1534 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1535 "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1536 "Free bounce pages");
1537 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1538 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1539 "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1540 "Reserved bounce pages");
1541 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1542 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1543 "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1544 "Active bounce pages");
1545 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1546 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1547 "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1548 "Total bounce requests (pages bounced)");
1549 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1550 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1551 "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1552 "Total bounce requests that were deferred");
1553 SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1554 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1555 "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1556 SYSCTL_ADD_ULONG(busdma_sysctl_tree(bz),
1557 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1558 "alignment", CTLFLAG_RD, &bz->alignment, "");
1564 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1566 struct bounce_zone *bz;
1569 bz = dmat->bounce_zone;
1571 while (numpages > 0) {
1572 struct bounce_page *bpage;
1574 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_BUSDMA,
1579 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_BOUNCE,
1580 M_NOWAIT, 0ul, bz->lowaddr, PAGE_SIZE, 0);
1581 if (bpage->vaddr == 0) {
1582 free(bpage, M_BUSDMA);
1585 bpage->busaddr = pmap_kextract(bpage->vaddr);
1586 mtx_lock(&bounce_lock);
1587 STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1591 mtx_unlock(&bounce_lock);
1599 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1601 struct bounce_zone *bz;
1604 mtx_assert(&bounce_lock, MA_OWNED);
1605 bz = dmat->bounce_zone;
1606 pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1607 if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1608 return (map->pagesneeded - (map->pagesreserved + pages));
1609 bz->free_bpages -= pages;
1610 bz->reserved_bpages += pages;
1611 map->pagesreserved += pages;
1612 pages = map->pagesneeded - map->pagesreserved;
1618 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1619 bus_addr_t addr, bus_size_t size)
1621 struct bounce_zone *bz;
1622 struct bounce_page *bpage;
1624 KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1625 KASSERT(map != NULL, ("add_bounce_page: bad map %p", map));
1627 bz = dmat->bounce_zone;
1628 if (map->pagesneeded == 0)
1629 panic("add_bounce_page: map doesn't need any pages");
1632 if (map->pagesreserved == 0)
1633 panic("add_bounce_page: map doesn't need any pages");
1634 map->pagesreserved--;
1636 mtx_lock(&bounce_lock);
1637 bpage = STAILQ_FIRST(&bz->bounce_page_list);
1639 panic("add_bounce_page: free page list is empty");
1641 STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1642 bz->reserved_bpages--;
1643 bz->active_bpages++;
1644 mtx_unlock(&bounce_lock);
1646 if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1647 /* Page offset needs to be preserved. */
1648 bpage->vaddr |= addr & PAGE_MASK;
1649 bpage->busaddr |= addr & PAGE_MASK;
1651 bpage->datavaddr = vaddr;
1652 bpage->datapage = PHYS_TO_VM_PAGE(addr);
1653 bpage->dataoffs = addr & PAGE_MASK;
1654 bpage->datacount = size;
1655 STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1656 return (bpage->busaddr);
1660 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1662 struct bus_dmamap *map;
1663 struct bounce_zone *bz;
1665 bz = dmat->bounce_zone;
1666 bpage->datavaddr = 0;
1667 bpage->datacount = 0;
1668 if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1670 * Reset the bounce page to start at offset 0. Other uses
1671 * of this bounce page may need to store a full page of
1672 * data and/or assume it starts on a page boundary.
1674 bpage->vaddr &= ~PAGE_MASK;
1675 bpage->busaddr &= ~PAGE_MASK;
1678 mtx_lock(&bounce_lock);
1679 STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1681 bz->active_bpages--;
1682 if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1683 if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1684 STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1685 STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1687 busdma_swi_pending = 1;
1688 bz->total_deferred++;
1689 swi_sched(vm_ih, 0);
1692 mtx_unlock(&bounce_lock);
1699 struct bus_dmamap *map;
1701 mtx_lock(&bounce_lock);
1702 while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1703 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1704 mtx_unlock(&bounce_lock);
1706 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_LOCK);
1707 bus_dmamap_load_mem(map->dmat, map, &map->mem, map->callback,
1708 map->callback_arg, BUS_DMA_WAITOK);
1709 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_UNLOCK);
1710 mtx_lock(&bounce_lock);
1712 mtx_unlock(&bounce_lock);