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.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 newtag->flags |= parent->flags & BUS_DMA_COHERENT;
495 if (newtag->boundary == 0)
496 newtag->boundary = parent->boundary;
497 else if (parent->boundary != 0)
498 newtag->boundary = MIN(parent->boundary,
500 if (newtag->filter == NULL) {
502 * Short circuit to looking at our parent directly
503 * since we have encapsulated all of its information
505 newtag->filter = parent->filter;
506 newtag->filterarg = parent->filterarg;
507 newtag->parent = parent->parent;
509 if (newtag->parent != NULL)
510 atomic_add_int(&parent->ref_count, 1);
513 if (exclusion_bounce_check(newtag->lowaddr, newtag->highaddr))
514 newtag->flags |= BUS_DMA_EXCL_BOUNCE;
515 if (alignment_bounce(newtag, 1))
516 newtag->flags |= BUS_DMA_ALIGN_BOUNCE;
519 * Any request can auto-bounce due to cacheline alignment, in addition
520 * to any alignment or boundary specifications in the tag, so if the
521 * ALLOCNOW flag is set, there's always work to do.
523 if ((flags & BUS_DMA_ALLOCNOW) != 0) {
524 struct bounce_zone *bz;
526 * Round size up to a full page, and add one more page because
527 * there can always be one more boundary crossing than the
528 * number of pages in a transfer.
530 maxsize = roundup2(maxsize, PAGE_SIZE) + PAGE_SIZE;
532 if ((error = alloc_bounce_zone(newtag)) != 0) {
533 free(newtag, M_BUSDMA);
536 bz = newtag->bounce_zone;
538 if (ptoa(bz->total_bpages) < maxsize) {
541 pages = atop(maxsize) - bz->total_bpages;
543 /* Add pages to our bounce pool */
544 if (alloc_bounce_pages(newtag, pages) < pages)
547 /* Performed initial allocation */
548 newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
550 newtag->bounce_zone = NULL;
553 free(newtag, M_BUSDMA);
555 atomic_add_32(&tags_total, 1);
558 CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
559 __func__, newtag, (newtag != NULL ? newtag->flags : 0), error);
564 bus_dma_tag_destroy(bus_dma_tag_t dmat)
566 bus_dma_tag_t dmat_copy;
574 if (dmat->map_count != 0) {
579 while (dmat != NULL) {
580 bus_dma_tag_t parent;
582 parent = dmat->parent;
583 atomic_subtract_int(&dmat->ref_count, 1);
584 if (dmat->ref_count == 0) {
585 atomic_subtract_32(&tags_total, 1);
586 free(dmat, M_BUSDMA);
588 * Last reference count, so
589 * release our reference
590 * count on our parent.
598 CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
603 allocate_bz_and_pages(bus_dma_tag_t dmat, bus_dmamap_t mapp)
605 struct bounce_zone *bz;
609 if (dmat->bounce_zone == NULL)
610 if ((error = alloc_bounce_zone(dmat)) != 0)
612 bz = dmat->bounce_zone;
613 /* Initialize the new map */
614 STAILQ_INIT(&(mapp->bpages));
617 * Attempt to add pages to our pool on a per-instance basis up to a sane
618 * limit. Even if the tag isn't flagged as COULD_BOUNCE due to
619 * alignment and boundary constraints, it could still auto-bounce due to
620 * cacheline alignment, which requires at most two bounce pages.
622 if (dmat->flags & BUS_DMA_COULD_BOUNCE)
623 maxpages = MAX_BPAGES;
625 maxpages = 2 * bz->map_count;
626 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0 ||
627 (bz->map_count > 0 && bz->total_bpages < maxpages)) {
630 pages = atop(roundup2(dmat->maxsize, PAGE_SIZE)) + 1;
631 pages = MIN(maxpages - bz->total_bpages, pages);
632 pages = MAX(pages, 2);
633 if (alloc_bounce_pages(dmat, pages) < pages)
636 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0)
637 dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
644 allocate_map(bus_dma_tag_t dmat, int mflags)
646 int mapsize, segsize;
650 * Allocate the map. The map structure ends with an embedded
651 * variable-sized array of sync_list structures. Following that
652 * we allocate enough extra space to hold the array of bus_dma_segments.
654 KASSERT(dmat->nsegments <= MAX_DMA_SEGMENTS,
655 ("cannot allocate %u dma segments (max is %u)",
656 dmat->nsegments, MAX_DMA_SEGMENTS));
657 segsize = sizeof(struct bus_dma_segment) * dmat->nsegments;
658 mapsize = sizeof(*map) + sizeof(struct sync_list) * dmat->nsegments;
659 map = malloc(mapsize + segsize, M_BUSDMA, mflags | M_ZERO);
661 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
664 map->segments = (bus_dma_segment_t *)((uintptr_t)map + mapsize);
669 * Allocate a handle for mapping from kva/uva/physical
670 * address space into bus device space.
673 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
678 *mapp = map = allocate_map(dmat, M_NOWAIT);
680 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
685 * Bouncing might be required if the driver asks for an exclusion
686 * region, a data alignment that is stricter than 1, or DMA that begins
687 * or ends with a partial cacheline. Whether bouncing will actually
688 * happen can't be known until mapping time, but we need to pre-allocate
689 * resources now because we might not be allowed to at mapping time.
691 error = allocate_bz_and_pages(dmat, map);
697 if (map->flags & DMAMAP_COHERENT)
698 atomic_add_32(&maps_coherent, 1);
699 atomic_add_32(&maps_total, 1);
706 * Destroy a handle for mapping from kva/uva/physical
707 * address space into bus device space.
710 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
713 if (STAILQ_FIRST(&map->bpages) != NULL || map->sync_count != 0) {
714 CTR3(KTR_BUSDMA, "%s: tag %p error %d",
715 __func__, dmat, EBUSY);
718 if (dmat->bounce_zone)
719 dmat->bounce_zone->map_count--;
720 if (map->flags & DMAMAP_COHERENT)
721 atomic_subtract_32(&maps_coherent, 1);
722 atomic_subtract_32(&maps_total, 1);
725 CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
730 * Allocate a piece of memory that can be efficiently mapped into bus device
731 * space based on the constraints listed in the dma tag. Returns a pointer to
732 * the allocated memory, and a pointer to an associated bus_dmamap.
735 bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
738 busdma_bufalloc_t ba;
739 struct busdma_bufzone *bufzone;
741 vm_memattr_t memattr;
744 if (flags & BUS_DMA_NOWAIT)
748 if (flags & BUS_DMA_ZERO)
751 *mapp = map = allocate_map(dmat, mflags);
753 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
754 __func__, dmat, dmat->flags, ENOMEM);
757 map->flags = DMAMAP_DMAMEM_ALLOC;
759 /* For coherent memory, set the map flag that disables sync ops. */
760 if (flags & BUS_DMA_COHERENT)
761 map->flags |= DMAMAP_COHERENT;
764 * Choose a busdma buffer allocator based on memory type flags.
765 * If the tag's COHERENT flag is set, that means normal memory
766 * is already coherent, use the normal allocator.
768 if ((flags & BUS_DMA_COHERENT) &&
769 ((dmat->flags & BUS_DMA_COHERENT) == 0)) {
770 memattr = VM_MEMATTR_UNCACHEABLE;
771 ba = coherent_allocator;
773 memattr = VM_MEMATTR_DEFAULT;
774 ba = standard_allocator;
778 * Try to find a bufzone in the allocator that holds a cache of buffers
779 * of the right size for this request. If the buffer is too big to be
780 * held in the allocator cache, this returns NULL.
782 bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
785 * Allocate the buffer from the uma(9) allocator if...
786 * - It's small enough to be in the allocator (bufzone not NULL).
787 * - The alignment constraint isn't larger than the allocation size
788 * (the allocator aligns buffers to their size boundaries).
789 * - There's no need to handle lowaddr/highaddr exclusion zones.
790 * else allocate non-contiguous pages if...
791 * - The page count that could get allocated doesn't exceed
792 * nsegments also when the maximum segment size is less
794 * - The alignment constraint isn't larger than a page boundary.
795 * - There are no boundary-crossing constraints.
796 * else allocate a block of contiguous pages because one or more of the
797 * constraints is something that only the contig allocator can fulfill.
799 if (bufzone != NULL && dmat->alignment <= bufzone->size &&
800 !exclusion_bounce(dmat)) {
801 *vaddr = uma_zalloc(bufzone->umazone, mflags);
802 } else if (dmat->nsegments >=
803 howmany(dmat->maxsize, MIN(dmat->maxsegsz, PAGE_SIZE)) &&
804 dmat->alignment <= PAGE_SIZE &&
805 (dmat->boundary % PAGE_SIZE) == 0) {
806 *vaddr = (void *)kmem_alloc_attr(kernel_arena, dmat->maxsize,
807 mflags, 0, dmat->lowaddr, memattr);
809 *vaddr = (void *)kmem_alloc_contig(kernel_arena, dmat->maxsize,
810 mflags, 0, dmat->lowaddr, dmat->alignment, dmat->boundary,
813 if (*vaddr == NULL) {
814 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
815 __func__, dmat, dmat->flags, ENOMEM);
820 if (map->flags & DMAMAP_COHERENT)
821 atomic_add_32(&maps_coherent, 1);
822 atomic_add_32(&maps_dmamem, 1);
823 atomic_add_32(&maps_total, 1);
826 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
827 __func__, dmat, dmat->flags, 0);
832 * Free a piece of memory that was allocated via bus_dmamem_alloc, along with
833 * its associated map.
836 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
838 struct busdma_bufzone *bufzone;
839 busdma_bufalloc_t ba;
841 if ((map->flags & DMAMAP_COHERENT) &&
842 ((dmat->flags & BUS_DMA_COHERENT) == 0))
843 ba = coherent_allocator;
845 ba = standard_allocator;
847 bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
849 if (bufzone != NULL && dmat->alignment <= bufzone->size &&
850 !exclusion_bounce(dmat))
851 uma_zfree(bufzone->umazone, vaddr);
853 kmem_free(kernel_arena, (vm_offset_t)vaddr, dmat->maxsize);
856 if (map->flags & DMAMAP_COHERENT)
857 atomic_subtract_32(&maps_coherent, 1);
858 atomic_subtract_32(&maps_total, 1);
859 atomic_subtract_32(&maps_dmamem, 1);
861 CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat, dmat->flags);
865 _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
866 bus_size_t buflen, int flags)
871 if (map->pagesneeded == 0) {
872 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
873 " map= %p, pagesneeded= %d",
874 dmat->lowaddr, dmat->boundary, dmat->alignment,
875 map, map->pagesneeded);
877 * Count the number of bounce pages
878 * needed in order to complete this transfer
881 while (buflen != 0) {
882 sgsize = MIN(buflen, dmat->maxsegsz);
883 if (must_bounce(dmat, map, curaddr, sgsize) != 0) {
885 PAGE_SIZE - (curaddr & PAGE_MASK));
891 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
896 _bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap, bus_dmamap_t map,
897 void *buf, bus_size_t buflen, int flags)
900 vm_offset_t vendaddr;
903 if (map->pagesneeded == 0) {
904 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
905 " map= %p, pagesneeded= %d",
906 dmat->lowaddr, dmat->boundary, dmat->alignment,
907 map, map->pagesneeded);
909 * Count the number of bounce pages
910 * needed in order to complete this transfer
912 vaddr = (vm_offset_t)buf;
913 vendaddr = (vm_offset_t)buf + buflen;
915 while (vaddr < vendaddr) {
916 if (__predict_true(pmap == kernel_pmap))
917 paddr = pmap_kextract(vaddr);
919 paddr = pmap_extract(pmap, vaddr);
920 if (must_bounce(dmat, map, paddr,
921 min(vendaddr - vaddr, (PAGE_SIZE - ((vm_offset_t)vaddr &
922 PAGE_MASK)))) != 0) {
925 vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
928 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
933 _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int flags)
936 /* Reserve Necessary Bounce Pages */
937 mtx_lock(&bounce_lock);
938 if (flags & BUS_DMA_NOWAIT) {
939 if (reserve_bounce_pages(dmat, map, 0) != 0) {
940 map->pagesneeded = 0;
941 mtx_unlock(&bounce_lock);
945 if (reserve_bounce_pages(dmat, map, 1) != 0) {
946 /* Queue us for resources */
947 STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
948 mtx_unlock(&bounce_lock);
949 return (EINPROGRESS);
952 mtx_unlock(&bounce_lock);
958 * Add a single contiguous physical range to the segment list.
961 _bus_dmamap_addseg(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t curaddr,
962 bus_size_t sgsize, bus_dma_segment_t *segs, int *segp)
964 bus_addr_t baddr, bmask;
968 * Make sure we don't cross any boundaries.
970 bmask = ~(dmat->boundary - 1);
971 if (dmat->boundary > 0) {
972 baddr = (curaddr + dmat->boundary) & bmask;
973 if (sgsize > (baddr - curaddr))
974 sgsize = (baddr - curaddr);
978 * Insert chunk into a segment, coalescing with
979 * previous segment if possible.
984 segs[seg].ds_addr = curaddr;
985 segs[seg].ds_len = sgsize;
987 if (curaddr == segs[seg].ds_addr + segs[seg].ds_len &&
988 (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
989 (dmat->boundary == 0 ||
990 (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
991 segs[seg].ds_len += sgsize;
993 if (++seg >= dmat->nsegments)
995 segs[seg].ds_addr = curaddr;
996 segs[seg].ds_len = sgsize;
1004 * Utility function to load a physical buffer. segp contains
1005 * the starting segment on entrace, and the ending segment on exit.
1008 _bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
1009 bus_size_t buflen, int flags, bus_dma_segment_t *segs, int *segp)
1012 bus_addr_t sl_end = 0;
1014 struct sync_list *sl;
1018 segs = map->segments;
1020 counter_u64_add(maploads_total, 1);
1021 counter_u64_add(maploads_physmem, 1);
1023 if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1024 _bus_dmamap_count_phys(dmat, map, buf, buflen, flags);
1025 if (map->pagesneeded != 0) {
1026 counter_u64_add(maploads_bounced, 1);
1027 error = _bus_dmamap_reserve_pages(dmat, map, flags);
1033 sl = map->slist + map->sync_count - 1;
1035 while (buflen > 0) {
1037 sgsize = MIN(buflen, dmat->maxsegsz);
1038 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1040 sgsize = MIN(sgsize, PAGE_SIZE - (curaddr & PAGE_MASK));
1041 curaddr = add_bounce_page(dmat, map, 0, curaddr,
1043 } else if ((dmat->flags & BUS_DMA_COHERENT) == 0) {
1044 if (map->sync_count > 0)
1045 sl_end = sl->paddr + sl->datacount;
1047 if (map->sync_count == 0 || curaddr != sl_end) {
1048 if (++map->sync_count > dmat->nsegments)
1052 sl->paddr = curaddr;
1053 sl->datacount = sgsize;
1054 sl->pages = PHYS_TO_VM_PAGE(curaddr);
1055 KASSERT(sl->pages != NULL,
1056 ("%s: page at PA:0x%08lx is not in "
1057 "vm_page_array", __func__, curaddr));
1059 sl->datacount += sgsize;
1061 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1073 bus_dmamap_unload(dmat, map);
1074 return (EFBIG); /* XXX better return value here? */
1080 _bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map,
1081 struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
1082 bus_dma_segment_t *segs, int *segp)
1085 return (bus_dmamap_load_ma_triv(dmat, map, ma, tlen, ma_offs, flags,
1090 * Utility function to load a linear buffer. segp contains
1091 * the starting segment on entrance, and the ending segment on exit.
1094 _bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
1095 bus_size_t buflen, pmap_t pmap, int flags, bus_dma_segment_t *segs,
1100 bus_addr_t sl_pend = 0;
1101 vm_offset_t kvaddr, vaddr, sl_vend = 0;
1102 struct sync_list *sl;
1105 counter_u64_add(maploads_total, 1);
1106 if (map->flags & DMAMAP_COHERENT)
1107 counter_u64_add(maploads_coherent, 1);
1108 if (map->flags & DMAMAP_DMAMEM_ALLOC)
1109 counter_u64_add(maploads_dmamem, 1);
1112 segs = map->segments;
1114 if (flags & BUS_DMA_LOAD_MBUF) {
1115 counter_u64_add(maploads_mbuf, 1);
1116 map->flags |= DMAMAP_MBUF;
1119 if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1120 _bus_dmamap_count_pages(dmat, pmap, map, buf, buflen, flags);
1121 if (map->pagesneeded != 0) {
1122 counter_u64_add(maploads_bounced, 1);
1123 error = _bus_dmamap_reserve_pages(dmat, map, flags);
1129 sl = map->slist + map->sync_count - 1;
1130 vaddr = (vm_offset_t)buf;
1132 while (buflen > 0) {
1134 * Get the physical address for this segment.
1136 if (__predict_true(pmap == kernel_pmap)) {
1137 curaddr = pmap_kextract(vaddr);
1140 curaddr = pmap_extract(pmap, vaddr);
1145 * Compute the segment size, and adjust counts.
1147 sgsize = PAGE_SIZE - (curaddr & PAGE_MASK);
1148 if (sgsize > dmat->maxsegsz)
1149 sgsize = dmat->maxsegsz;
1150 if (buflen < sgsize)
1153 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1155 curaddr = add_bounce_page(dmat, map, kvaddr, curaddr,
1157 } else if ((dmat->flags & BUS_DMA_COHERENT) == 0) {
1158 if (map->sync_count > 0) {
1159 sl_pend = sl->paddr + sl->datacount;
1160 sl_vend = sl->vaddr + sl->datacount;
1163 if (map->sync_count == 0 ||
1164 (kvaddr != 0 && kvaddr != sl_vend) ||
1165 (curaddr != sl_pend)) {
1167 if (++map->sync_count > dmat->nsegments)
1171 sl->paddr = curaddr;
1175 sl->pages = PHYS_TO_VM_PAGE(curaddr);
1176 KASSERT(sl->pages != NULL,
1177 ("%s: page at PA:0x%08lx is not "
1178 "in vm_page_array", __func__,
1181 sl->datacount = sgsize;
1183 sl->datacount += sgsize;
1185 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1198 bus_dmamap_unload(dmat, map);
1199 return (EFBIG); /* XXX better return value here? */
1205 _bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map, struct memdesc *mem,
1206 bus_dmamap_callback_t *callback, void *callback_arg)
1211 map->callback = callback;
1212 map->callback_arg = callback_arg;
1216 _bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map,
1217 bus_dma_segment_t *segs, int nsegs, int error)
1221 segs = map->segments;
1226 * Release the mapping held by map.
1229 bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1231 struct bounce_page *bpage;
1232 struct bounce_zone *bz;
1234 if ((bz = dmat->bounce_zone) != NULL) {
1235 while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1236 STAILQ_REMOVE_HEAD(&map->bpages, links);
1237 free_bounce_page(dmat, bpage);
1240 bz = dmat->bounce_zone;
1241 bz->free_bpages += map->pagesreserved;
1242 bz->reserved_bpages -= map->pagesreserved;
1243 map->pagesreserved = 0;
1244 map->pagesneeded = 0;
1246 map->sync_count = 0;
1247 map->flags &= ~DMAMAP_MBUF;
1251 dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size)
1254 * Write back any partial cachelines immediately before and
1255 * after the DMA region. We don't need to round the address
1256 * down to the nearest cacheline or specify the exact size,
1257 * as dcache_wb_poc() will do the rounding for us and works
1258 * at cacheline granularity.
1260 if (va & BUSDMA_DCACHE_MASK)
1261 dcache_wb_poc(va, pa, 1);
1262 if ((va + size) & BUSDMA_DCACHE_MASK)
1263 dcache_wb_poc(va + size, pa + size, 1);
1265 dcache_inv_poc_dma(va, pa, size);
1269 dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op)
1271 uint32_t len, offset;
1274 vm_offset_t va, tempva;
1277 offset = sl->paddr & PAGE_MASK;
1279 size = sl->datacount;
1282 for ( ; size != 0; size -= len, pa += len, offset = 0, ++m) {
1284 if (sl->vaddr == 0) {
1285 len = min(PAGE_SIZE - offset, size);
1286 tempva = pmap_quick_enter_page(m);
1287 va = tempva | offset;
1288 KASSERT(pa == (VM_PAGE_TO_PHYS(m) | offset),
1289 ("unexpected vm_page_t phys: 0x%08x != 0x%08x",
1290 VM_PAGE_TO_PHYS(m) | offset, pa));
1292 len = sl->datacount;
1297 case BUS_DMASYNC_PREWRITE:
1298 case BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD:
1299 dcache_wb_poc(va, pa, len);
1301 case BUS_DMASYNC_PREREAD:
1303 * An mbuf may start in the middle of a cacheline. There
1304 * will be no cpu writes to the beginning of that line
1305 * (which contains the mbuf header) while dma is in
1306 * progress. Handle that case by doing a writeback of
1307 * just the first cacheline before invalidating the
1308 * overall buffer. Any mbuf in a chain may have this
1309 * misalignment. Buffers which are not mbufs bounce if
1310 * they are not aligned to a cacheline.
1312 dma_preread_safe(va, pa, len);
1314 case BUS_DMASYNC_POSTREAD:
1315 case BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE:
1316 dcache_inv_poc(va, pa, len);
1319 panic("unsupported combination of sync operations: "
1324 pmap_quick_remove_page(tempva);
1329 bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1331 struct bounce_page *bpage;
1332 struct sync_list *sl, *end;
1333 vm_offset_t datavaddr, tempvaddr;
1335 if (op == BUS_DMASYNC_POSTWRITE)
1339 * If the buffer was from user space, it is possible that this is not
1340 * the same vm map, especially on a POST operation. It's not clear that
1341 * dma on userland buffers can work at all right now. To be safe, until
1342 * we're able to test direct userland dma, panic on a map mismatch.
1344 if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1346 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1347 "performing bounce", __func__, dmat, dmat->flags, op);
1350 * For PREWRITE do a writeback. Clean the caches from the
1351 * innermost to the outermost levels.
1353 if (op & BUS_DMASYNC_PREWRITE) {
1354 while (bpage != NULL) {
1356 datavaddr = bpage->datavaddr;
1357 if (datavaddr == 0) {
1358 tempvaddr = pmap_quick_enter_page(
1360 datavaddr = tempvaddr | bpage->dataoffs;
1362 bcopy((void *)datavaddr, (void *)bpage->vaddr,
1365 pmap_quick_remove_page(tempvaddr);
1366 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1367 dcache_wb_poc(bpage->vaddr,
1368 bpage->busaddr, bpage->datacount);
1369 bpage = STAILQ_NEXT(bpage, links);
1371 dmat->bounce_zone->total_bounced++;
1375 * Do an invalidate for PREREAD unless a writeback was already
1376 * done above due to PREWRITE also being set. The reason for a
1377 * PREREAD invalidate is to prevent dirty lines currently in the
1378 * cache from being evicted during the DMA. If a writeback was
1379 * done due to PREWRITE also being set there will be no dirty
1380 * lines and the POSTREAD invalidate handles the rest. The
1381 * invalidate is done from the innermost to outermost level. If
1382 * L2 were done first, a dirty cacheline could be automatically
1383 * evicted from L1 before we invalidated it, re-dirtying the L2.
1385 if ((op & BUS_DMASYNC_PREREAD) && !(op & BUS_DMASYNC_PREWRITE)) {
1386 bpage = STAILQ_FIRST(&map->bpages);
1387 while (bpage != NULL) {
1388 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1389 dcache_inv_poc_dma(bpage->vaddr,
1390 bpage->busaddr, bpage->datacount);
1391 bpage = STAILQ_NEXT(bpage, links);
1396 * Re-invalidate the caches on a POSTREAD, even though they were
1397 * already invalidated at PREREAD time. Aggressive prefetching
1398 * due to accesses to other data near the dma buffer could have
1399 * brought buffer data into the caches which is now stale. The
1400 * caches are invalidated from the outermost to innermost; the
1401 * prefetches could be happening right now, and if L1 were
1402 * invalidated first, stale L2 data could be prefetched into L1.
1404 if (op & BUS_DMASYNC_POSTREAD) {
1405 while (bpage != NULL) {
1406 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1407 dcache_inv_poc(bpage->vaddr,
1408 bpage->busaddr, bpage->datacount);
1410 datavaddr = bpage->datavaddr;
1411 if (datavaddr == 0) {
1412 tempvaddr = pmap_quick_enter_page(
1414 datavaddr = tempvaddr | bpage->dataoffs;
1416 bcopy((void *)bpage->vaddr, (void *)datavaddr,
1419 pmap_quick_remove_page(tempvaddr);
1420 bpage = STAILQ_NEXT(bpage, links);
1422 dmat->bounce_zone->total_bounced++;
1427 * For COHERENT memory no cache maintenance is necessary, but ensure all
1428 * writes have reached memory for the PREWRITE case. No action is
1429 * needed for a PREREAD without PREWRITE also set, because that would
1430 * imply that the cpu had written to the COHERENT buffer and expected
1431 * the dma device to see that change, and by definition a PREWRITE sync
1432 * is required to make that happen.
1434 if (map->flags & DMAMAP_COHERENT) {
1435 if (op & BUS_DMASYNC_PREWRITE) {
1437 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1438 cpu_l2cache_drain_writebuf();
1444 * Cache maintenance for normal (non-COHERENT non-bounce) buffers. All
1445 * the comments about the sequences for flushing cache levels in the
1446 * bounce buffer code above apply here as well. In particular, the fact
1447 * that the sequence is inner-to-outer for PREREAD invalidation and
1448 * outer-to-inner for POSTREAD invalidation is not a mistake.
1450 if (map->sync_count != 0) {
1451 sl = &map->slist[0];
1452 end = &map->slist[map->sync_count];
1453 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1454 "performing sync", __func__, dmat, dmat->flags, op);
1456 for ( ; sl != end; ++sl)
1457 dma_dcache_sync(sl, op);
1462 init_bounce_pages(void *dummy __unused)
1466 STAILQ_INIT(&bounce_zone_list);
1467 STAILQ_INIT(&bounce_map_waitinglist);
1468 STAILQ_INIT(&bounce_map_callbacklist);
1469 mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
1471 SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
1473 static struct sysctl_ctx_list *
1474 busdma_sysctl_tree(struct bounce_zone *bz)
1477 return (&bz->sysctl_tree);
1480 static struct sysctl_oid *
1481 busdma_sysctl_tree_top(struct bounce_zone *bz)
1484 return (bz->sysctl_tree_top);
1488 alloc_bounce_zone(bus_dma_tag_t dmat)
1490 struct bounce_zone *bz;
1492 /* Check to see if we already have a suitable zone */
1493 STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1494 if ((dmat->alignment <= bz->alignment) &&
1495 (dmat->lowaddr >= bz->lowaddr)) {
1496 dmat->bounce_zone = bz;
1501 if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_BUSDMA,
1502 M_NOWAIT | M_ZERO)) == NULL)
1505 STAILQ_INIT(&bz->bounce_page_list);
1506 bz->free_bpages = 0;
1507 bz->reserved_bpages = 0;
1508 bz->active_bpages = 0;
1509 bz->lowaddr = dmat->lowaddr;
1510 bz->alignment = MAX(dmat->alignment, PAGE_SIZE);
1512 snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1514 snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1515 STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1516 dmat->bounce_zone = bz;
1518 sysctl_ctx_init(&bz->sysctl_tree);
1519 bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
1520 SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1522 if (bz->sysctl_tree_top == NULL) {
1523 sysctl_ctx_free(&bz->sysctl_tree);
1524 return (0); /* XXX error code? */
1527 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1528 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1529 "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1530 "Total bounce pages");
1531 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1532 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1533 "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1534 "Free bounce pages");
1535 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1536 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1537 "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1538 "Reserved bounce pages");
1539 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1540 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1541 "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1542 "Active bounce pages");
1543 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1544 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1545 "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1546 "Total bounce requests (pages bounced)");
1547 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1548 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1549 "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1550 "Total bounce requests that were deferred");
1551 SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1552 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1553 "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1554 SYSCTL_ADD_ULONG(busdma_sysctl_tree(bz),
1555 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1556 "alignment", CTLFLAG_RD, &bz->alignment, "");
1562 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1564 struct bounce_zone *bz;
1567 bz = dmat->bounce_zone;
1569 while (numpages > 0) {
1570 struct bounce_page *bpage;
1572 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_BUSDMA,
1577 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_BOUNCE,
1578 M_NOWAIT, 0ul, bz->lowaddr, PAGE_SIZE, 0);
1579 if (bpage->vaddr == 0) {
1580 free(bpage, M_BUSDMA);
1583 bpage->busaddr = pmap_kextract(bpage->vaddr);
1584 mtx_lock(&bounce_lock);
1585 STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1589 mtx_unlock(&bounce_lock);
1597 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1599 struct bounce_zone *bz;
1602 mtx_assert(&bounce_lock, MA_OWNED);
1603 bz = dmat->bounce_zone;
1604 pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1605 if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1606 return (map->pagesneeded - (map->pagesreserved + pages));
1607 bz->free_bpages -= pages;
1608 bz->reserved_bpages += pages;
1609 map->pagesreserved += pages;
1610 pages = map->pagesneeded - map->pagesreserved;
1616 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1617 bus_addr_t addr, bus_size_t size)
1619 struct bounce_zone *bz;
1620 struct bounce_page *bpage;
1622 KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1623 KASSERT(map != NULL, ("add_bounce_page: bad map %p", map));
1625 bz = dmat->bounce_zone;
1626 if (map->pagesneeded == 0)
1627 panic("add_bounce_page: map doesn't need any pages");
1630 if (map->pagesreserved == 0)
1631 panic("add_bounce_page: map doesn't need any pages");
1632 map->pagesreserved--;
1634 mtx_lock(&bounce_lock);
1635 bpage = STAILQ_FIRST(&bz->bounce_page_list);
1637 panic("add_bounce_page: free page list is empty");
1639 STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1640 bz->reserved_bpages--;
1641 bz->active_bpages++;
1642 mtx_unlock(&bounce_lock);
1644 if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1645 /* Page offset needs to be preserved. */
1646 bpage->vaddr |= addr & PAGE_MASK;
1647 bpage->busaddr |= addr & PAGE_MASK;
1649 bpage->datavaddr = vaddr;
1650 bpage->datapage = PHYS_TO_VM_PAGE(addr);
1651 bpage->dataoffs = addr & PAGE_MASK;
1652 bpage->datacount = size;
1653 STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1654 return (bpage->busaddr);
1658 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1660 struct bus_dmamap *map;
1661 struct bounce_zone *bz;
1663 bz = dmat->bounce_zone;
1664 bpage->datavaddr = 0;
1665 bpage->datacount = 0;
1666 if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1668 * Reset the bounce page to start at offset 0. Other uses
1669 * of this bounce page may need to store a full page of
1670 * data and/or assume it starts on a page boundary.
1672 bpage->vaddr &= ~PAGE_MASK;
1673 bpage->busaddr &= ~PAGE_MASK;
1676 mtx_lock(&bounce_lock);
1677 STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1679 bz->active_bpages--;
1680 if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1681 if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1682 STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1683 STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1685 busdma_swi_pending = 1;
1686 bz->total_deferred++;
1687 swi_sched(vm_ih, 0);
1690 mtx_unlock(&bounce_lock);
1697 struct bus_dmamap *map;
1699 mtx_lock(&bounce_lock);
1700 while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1701 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1702 mtx_unlock(&bounce_lock);
1704 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_LOCK);
1705 bus_dmamap_load_mem(map->dmat, map, &map->mem, map->callback,
1706 map->callback_arg, BUS_DMA_WAITOK);
1707 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_UNLOCK);
1708 mtx_lock(&bounce_lock);
1710 mtx_unlock(&bounce_lock);