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_param.h>
56 #include <vm/vm_page.h>
57 #include <vm/vm_phys.h>
58 #include <vm/vm_map.h>
59 #include <vm/vm_extern.h>
60 #include <vm/vm_kern.h>
62 #include <machine/atomic.h>
63 #include <machine/bus.h>
64 #include <machine/cpu.h>
65 #include <machine/md_var.h>
67 #define BUSDMA_DCACHE_ALIGN cpuinfo.dcache_line_size
68 #define BUSDMA_DCACHE_MASK cpuinfo.dcache_line_mask
71 #define MAX_DMA_SEGMENTS 4096
72 #define BUS_DMA_EXCL_BOUNCE BUS_DMA_BUS2
73 #define BUS_DMA_ALIGN_BOUNCE BUS_DMA_BUS3
74 #define BUS_DMA_COULD_BOUNCE (BUS_DMA_EXCL_BOUNCE | BUS_DMA_ALIGN_BOUNCE)
75 #define BUS_DMA_MIN_ALLOC_COMP BUS_DMA_BUS4
85 bus_dma_filter_t *filter;
93 bus_dma_lock_t *lockfunc;
95 struct bounce_zone *bounce_zone;
99 vm_offset_t vaddr; /* kva of bounce buffer */
100 bus_addr_t busaddr; /* Physical address */
101 vm_offset_t datavaddr; /* kva of client data */
102 vm_page_t datapage; /* physical page of client data */
103 vm_offset_t dataoffs; /* page offset of client data */
104 bus_size_t datacount; /* client data count */
105 STAILQ_ENTRY(bounce_page) links;
109 vm_offset_t vaddr; /* kva of client data */
110 bus_addr_t paddr; /* physical address */
111 vm_page_t pages; /* starting page of client data */
112 bus_size_t datacount; /* client data count */
115 int busdma_swi_pending;
118 STAILQ_ENTRY(bounce_zone) links;
119 STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
127 bus_size_t alignment;
131 struct sysctl_ctx_list sysctl_tree;
132 struct sysctl_oid *sysctl_tree_top;
135 static struct mtx bounce_lock;
136 static int total_bpages;
137 static int busdma_zonecount;
138 static uint32_t tags_total;
139 static uint32_t maps_total;
140 static uint32_t maps_dmamem;
141 static uint32_t maps_coherent;
142 static counter_u64_t maploads_total;
143 static counter_u64_t maploads_bounced;
144 static counter_u64_t maploads_coherent;
145 static counter_u64_t maploads_dmamem;
146 static counter_u64_t maploads_mbuf;
147 static counter_u64_t maploads_physmem;
149 static STAILQ_HEAD(, bounce_zone) bounce_zone_list;
151 SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
152 SYSCTL_UINT(_hw_busdma, OID_AUTO, tags_total, CTLFLAG_RD, &tags_total, 0,
153 "Number of active tags");
154 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_total, CTLFLAG_RD, &maps_total, 0,
155 "Number of active maps");
156 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_dmamem, CTLFLAG_RD, &maps_dmamem, 0,
157 "Number of active maps for bus_dmamem_alloc buffers");
158 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_coherent, CTLFLAG_RD, &maps_coherent, 0,
159 "Number of active maps with BUS_DMA_COHERENT flag set");
160 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_total, CTLFLAG_RD,
161 &maploads_total, "Number of load operations performed");
162 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_bounced, CTLFLAG_RD,
163 &maploads_bounced, "Number of load operations that used bounce buffers");
164 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_coherent, CTLFLAG_RD,
165 &maploads_dmamem, "Number of load operations on BUS_DMA_COHERENT memory");
166 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_dmamem, CTLFLAG_RD,
167 &maploads_dmamem, "Number of load operations on bus_dmamem_alloc buffers");
168 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_mbuf, CTLFLAG_RD,
169 &maploads_mbuf, "Number of load operations for mbufs");
170 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_physmem, CTLFLAG_RD,
171 &maploads_physmem, "Number of load operations on physical buffers");
172 SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bpages, 0,
173 "Total bounce pages");
176 struct bp_list bpages;
181 bus_dmamap_callback_t *callback;
184 #define DMAMAP_COHERENT (1 << 0)
185 #define DMAMAP_DMAMEM_ALLOC (1 << 1)
186 #define DMAMAP_MBUF (1 << 2)
187 STAILQ_ENTRY(bus_dmamap) links;
188 bus_dma_segment_t *segments;
190 struct sync_list slist[];
193 static STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
194 static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist;
196 static void init_bounce_pages(void *dummy);
197 static int alloc_bounce_zone(bus_dma_tag_t dmat);
198 static int alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages);
199 static int reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
201 static bus_addr_t add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map,
202 vm_offset_t vaddr, bus_addr_t addr, bus_size_t size);
203 static void free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage);
204 static void _bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap,
205 bus_dmamap_t map, void *buf, bus_size_t buflen, int flags);
206 static void _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map,
207 vm_paddr_t buf, bus_size_t buflen, int flags);
208 static int _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
210 static void dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size);
211 static void dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op);
213 static busdma_bufalloc_t coherent_allocator; /* Cache of coherent buffers */
214 static busdma_bufalloc_t standard_allocator; /* Cache of standard buffers */
216 MALLOC_DEFINE(M_BUSDMA, "busdma", "busdma metadata");
217 MALLOC_DEFINE(M_BOUNCE, "bounce", "busdma bounce pages");
220 busdma_init(void *dummy)
224 maploads_total = counter_u64_alloc(M_WAITOK);
225 maploads_bounced = counter_u64_alloc(M_WAITOK);
226 maploads_coherent = counter_u64_alloc(M_WAITOK);
227 maploads_dmamem = counter_u64_alloc(M_WAITOK);
228 maploads_mbuf = counter_u64_alloc(M_WAITOK);
229 maploads_physmem = counter_u64_alloc(M_WAITOK);
233 /* Create a cache of buffers in standard (cacheable) memory. */
234 standard_allocator = busdma_bufalloc_create("buffer",
235 BUSDMA_DCACHE_ALIGN,/* minimum_alignment */
236 NULL, /* uma_alloc func */
237 NULL, /* uma_free func */
238 uma_flags); /* uma_zcreate_flags */
242 * Force UMA zone to allocate service structures like
243 * slabs using own allocator. uma_debug code performs
244 * atomic ops on uma_slab_t fields and safety of this
245 * operation is not guaranteed for write-back caches
247 uma_flags = UMA_ZONE_OFFPAGE;
250 * Create a cache of buffers in uncacheable memory, to implement the
251 * BUS_DMA_COHERENT (and potentially BUS_DMA_NOCACHE) flag.
253 coherent_allocator = busdma_bufalloc_create("coherent",
254 BUSDMA_DCACHE_ALIGN,/* minimum_alignment */
255 busdma_bufalloc_alloc_uncacheable,
256 busdma_bufalloc_free_uncacheable,
257 uma_flags); /* uma_zcreate_flags */
261 * This init historically used SI_SUB_VM, but now the init code requires
262 * malloc(9) using M_BUSDMA memory and the pcpu zones for counter(9), which get
263 * set up by SI_SUB_KMEM and SI_ORDER_LAST, so we'll go right after that by
264 * using SI_SUB_KMEM+1.
266 SYSINIT(busdma, SI_SUB_KMEM+1, SI_ORDER_FIRST, busdma_init, NULL);
269 * This routine checks the exclusion zone constraints from a tag against the
270 * physical RAM available on the machine. If a tag specifies an exclusion zone
271 * but there's no RAM in that zone, then we avoid allocating resources to bounce
272 * a request, and we can use any memory allocator (as opposed to needing
273 * kmem_alloc_contig() just because it can allocate pages in an address range).
275 * Most tags have BUS_SPACE_MAXADDR or BUS_SPACE_MAXADDR_32BIT (they are the
276 * same value on 32-bit architectures) as their lowaddr constraint, and we can't
277 * possibly have RAM at an address higher than the highest address we can
278 * express, so we take a fast out.
281 exclusion_bounce_check(vm_offset_t lowaddr, vm_offset_t highaddr)
285 if (lowaddr >= BUS_SPACE_MAXADDR)
288 for (i = 0; phys_avail[i] && phys_avail[i + 1]; i += 2) {
289 if ((lowaddr >= phys_avail[i] && lowaddr < phys_avail[i + 1]) ||
290 (lowaddr < phys_avail[i] && highaddr >= phys_avail[i]))
297 * Return true if the tag has an exclusion zone that could lead to bouncing.
300 exclusion_bounce(bus_dma_tag_t dmat)
303 return (dmat->flags & BUS_DMA_EXCL_BOUNCE);
307 * Return true if the given address does not fall on the alignment boundary.
310 alignment_bounce(bus_dma_tag_t dmat, bus_addr_t addr)
313 return (addr & (dmat->alignment - 1));
317 * Return true if the DMA should bounce because the start or end does not fall
318 * on a cacheline boundary (which would require a partial cacheline flush).
319 * COHERENT memory doesn't trigger cacheline flushes. Memory allocated by
320 * bus_dmamem_alloc() is always aligned to cacheline boundaries, and there's a
321 * strict rule that such memory cannot be accessed by the CPU while DMA is in
322 * progress (or by multiple DMA engines at once), so that it's always safe to do
323 * full cacheline flushes even if that affects memory outside the range of a
324 * given DMA operation that doesn't involve the full allocated buffer. If we're
325 * mapping an mbuf, that follows the same rules as a buffer we allocated.
328 cacheline_bounce(bus_dmamap_t map, bus_addr_t addr, bus_size_t size)
331 if (map->flags & (DMAMAP_DMAMEM_ALLOC | DMAMAP_COHERENT | DMAMAP_MBUF))
333 return ((addr | size) & BUSDMA_DCACHE_MASK);
337 * Return true if we might need to bounce the DMA described by addr and size.
339 * This is used to quick-check whether we need to do the more expensive work of
340 * checking the DMA page-by-page looking for alignment and exclusion bounces.
342 * Note that the addr argument might be either virtual or physical. It doesn't
343 * matter because we only look at the low-order bits, which are the same in both
344 * address spaces and maximum alignment of generic buffer is limited up to page
346 * Bouncing of buffers allocated by bus_dmamem_alloc()is not necessary, these
347 * always comply with the required rules (alignment, boundary, and address
351 might_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t addr,
355 KASSERT(map->flags & DMAMAP_DMAMEM_ALLOC ||
356 dmat->alignment <= PAGE_SIZE,
357 ("%s: unsupported alignment (0x%08lx) for buffer not "
358 "allocated by bus_dmamem_alloc()",
359 __func__, dmat->alignment));
361 return (!(map->flags & DMAMAP_DMAMEM_ALLOC) &&
362 ((dmat->flags & BUS_DMA_EXCL_BOUNCE) ||
363 alignment_bounce(dmat, addr) ||
364 cacheline_bounce(map, addr, size)));
368 * Return true if we must bounce the DMA described by paddr and size.
370 * Bouncing can be triggered by DMA that doesn't begin and end on cacheline
371 * boundaries, or doesn't begin on an alignment boundary, or falls within the
372 * exclusion zone of any tag in the ancestry chain.
374 * For exclusions, walk the chain of tags comparing paddr to the exclusion zone
375 * within each tag. If the tag has a filter function, use it to decide whether
376 * the DMA needs to bounce, otherwise any DMA within the zone bounces.
379 must_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t paddr,
383 if (cacheline_bounce(map, paddr, size))
387 * The tag already contains ancestors' alignment restrictions so this
388 * check doesn't need to be inside the loop.
390 if (alignment_bounce(dmat, paddr))
394 * Even though each tag has an exclusion zone that is a superset of its
395 * own and all its ancestors' exclusions, the exclusion zone of each tag
396 * up the chain must be checked within the loop, because the busdma
397 * rules say the filter function is called only when the address lies
398 * within the low-highaddr range of the tag that filterfunc belongs to.
400 while (dmat != NULL && exclusion_bounce(dmat)) {
401 if ((paddr >= dmat->lowaddr && paddr <= dmat->highaddr) &&
402 (dmat->filter == NULL ||
403 dmat->filter(dmat->filterarg, paddr) != 0))
412 * Convenience function for manipulating driver locks from busdma (during
413 * busdma_swi, for example). Drivers that don't provide their own locks
414 * should specify &Giant to dmat->lockfuncarg. Drivers that use their own
415 * non-mutex locking scheme don't have to use this at all.
418 busdma_lock_mutex(void *arg, bus_dma_lock_op_t op)
422 dmtx = (struct mtx *)arg;
431 panic("Unknown operation 0x%x for busdma_lock_mutex!", op);
436 * dflt_lock should never get called. It gets put into the dma tag when
437 * lockfunc == NULL, which is only valid if the maps that are associated
438 * with the tag are meant to never be defered.
439 * XXX Should have a way to identify which driver is responsible here.
442 dflt_lock(void *arg, bus_dma_lock_op_t op)
445 panic("driver error: busdma dflt_lock called");
449 * Allocate a device specific dma_tag.
452 bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
453 bus_addr_t boundary, bus_addr_t lowaddr, bus_addr_t highaddr,
454 bus_dma_filter_t *filter, void *filterarg, bus_size_t maxsize,
455 int nsegments, bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
456 void *lockfuncarg, bus_dma_tag_t *dmat)
458 bus_dma_tag_t newtag;
461 /* Basic sanity checking. */
462 KASSERT(boundary == 0 || powerof2(boundary),
463 ("dma tag boundary %lu, must be a power of 2", boundary));
464 KASSERT(boundary == 0 || boundary >= maxsegsz,
465 ("dma tag boundary %lu is < maxsegsz %lu\n", boundary, maxsegsz));
466 KASSERT(alignment != 0 && powerof2(alignment),
467 ("dma tag alignment %lu, must be non-zero power of 2", alignment));
468 KASSERT(maxsegsz != 0, ("dma tag maxsegsz must not be zero"));
470 /* Return a NULL tag on failure */
473 newtag = (bus_dma_tag_t)malloc(sizeof(*newtag), M_BUSDMA,
475 if (newtag == NULL) {
476 CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
477 __func__, newtag, 0, error);
481 newtag->parent = parent;
482 newtag->alignment = alignment;
483 newtag->boundary = boundary;
484 newtag->lowaddr = trunc_page((vm_paddr_t)lowaddr) + (PAGE_SIZE - 1);
485 newtag->highaddr = trunc_page((vm_paddr_t)highaddr) +
487 newtag->filter = filter;
488 newtag->filterarg = filterarg;
489 newtag->maxsize = maxsize;
490 newtag->nsegments = nsegments;
491 newtag->maxsegsz = maxsegsz;
492 newtag->flags = flags;
493 newtag->ref_count = 1; /* Count ourself */
494 newtag->map_count = 0;
495 if (lockfunc != NULL) {
496 newtag->lockfunc = lockfunc;
497 newtag->lockfuncarg = lockfuncarg;
499 newtag->lockfunc = dflt_lock;
500 newtag->lockfuncarg = NULL;
503 /* Take into account any restrictions imposed by our parent tag */
504 if (parent != NULL) {
505 newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
506 newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
507 newtag->alignment = MAX(parent->alignment, newtag->alignment);
508 newtag->flags |= parent->flags & BUS_DMA_COULD_BOUNCE;
509 newtag->flags |= parent->flags & BUS_DMA_COHERENT;
510 if (newtag->boundary == 0)
511 newtag->boundary = parent->boundary;
512 else if (parent->boundary != 0)
513 newtag->boundary = MIN(parent->boundary,
515 if (newtag->filter == NULL) {
517 * Short circuit to looking at our parent directly
518 * since we have encapsulated all of its information
520 newtag->filter = parent->filter;
521 newtag->filterarg = parent->filterarg;
522 newtag->parent = parent->parent;
524 if (newtag->parent != NULL)
525 atomic_add_int(&parent->ref_count, 1);
528 if (exclusion_bounce_check(newtag->lowaddr, newtag->highaddr))
529 newtag->flags |= BUS_DMA_EXCL_BOUNCE;
530 if (alignment_bounce(newtag, 1))
531 newtag->flags |= BUS_DMA_ALIGN_BOUNCE;
534 * Any request can auto-bounce due to cacheline alignment, in addition
535 * to any alignment or boundary specifications in the tag, so if the
536 * ALLOCNOW flag is set, there's always work to do.
538 if ((flags & BUS_DMA_ALLOCNOW) != 0) {
539 struct bounce_zone *bz;
541 * Round size up to a full page, and add one more page because
542 * there can always be one more boundary crossing than the
543 * number of pages in a transfer.
545 maxsize = roundup2(maxsize, PAGE_SIZE) + PAGE_SIZE;
547 if ((error = alloc_bounce_zone(newtag)) != 0) {
548 free(newtag, M_BUSDMA);
551 bz = newtag->bounce_zone;
553 if (ptoa(bz->total_bpages) < maxsize) {
556 pages = atop(maxsize) - bz->total_bpages;
558 /* Add pages to our bounce pool */
559 if (alloc_bounce_pages(newtag, pages) < pages)
562 /* Performed initial allocation */
563 newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
565 newtag->bounce_zone = NULL;
568 free(newtag, M_BUSDMA);
570 atomic_add_32(&tags_total, 1);
573 CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
574 __func__, newtag, (newtag != NULL ? newtag->flags : 0), error);
579 bus_dma_tag_set_domain(bus_dma_tag_t dmat, int domain)
586 bus_dma_tag_destroy(bus_dma_tag_t dmat)
588 bus_dma_tag_t dmat_copy;
596 if (dmat->map_count != 0) {
601 while (dmat != NULL) {
602 bus_dma_tag_t parent;
604 parent = dmat->parent;
605 atomic_subtract_int(&dmat->ref_count, 1);
606 if (dmat->ref_count == 0) {
607 atomic_subtract_32(&tags_total, 1);
608 free(dmat, M_BUSDMA);
610 * Last reference count, so
611 * release our reference
612 * count on our parent.
620 CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
625 allocate_bz_and_pages(bus_dma_tag_t dmat, bus_dmamap_t mapp)
627 struct bounce_zone *bz;
631 if (dmat->bounce_zone == NULL)
632 if ((error = alloc_bounce_zone(dmat)) != 0)
634 bz = dmat->bounce_zone;
635 /* Initialize the new map */
636 STAILQ_INIT(&(mapp->bpages));
639 * Attempt to add pages to our pool on a per-instance basis up to a sane
640 * limit. Even if the tag isn't flagged as COULD_BOUNCE due to
641 * alignment and boundary constraints, it could still auto-bounce due to
642 * cacheline alignment, which requires at most two bounce pages.
644 if (dmat->flags & BUS_DMA_COULD_BOUNCE)
645 maxpages = MAX_BPAGES;
647 maxpages = 2 * bz->map_count;
648 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0 ||
649 (bz->map_count > 0 && bz->total_bpages < maxpages)) {
652 pages = atop(roundup2(dmat->maxsize, PAGE_SIZE)) + 1;
653 pages = MIN(maxpages - bz->total_bpages, pages);
654 pages = MAX(pages, 2);
655 if (alloc_bounce_pages(dmat, pages) < pages)
658 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0)
659 dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
666 allocate_map(bus_dma_tag_t dmat, int mflags)
668 int mapsize, segsize;
672 * Allocate the map. The map structure ends with an embedded
673 * variable-sized array of sync_list structures. Following that
674 * we allocate enough extra space to hold the array of bus_dma_segments.
676 KASSERT(dmat->nsegments <= MAX_DMA_SEGMENTS,
677 ("cannot allocate %u dma segments (max is %u)",
678 dmat->nsegments, MAX_DMA_SEGMENTS));
679 segsize = sizeof(struct bus_dma_segment) * dmat->nsegments;
680 mapsize = sizeof(*map) + sizeof(struct sync_list) * dmat->nsegments;
681 map = malloc(mapsize + segsize, M_BUSDMA, mflags | M_ZERO);
683 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
686 map->segments = (bus_dma_segment_t *)((uintptr_t)map + mapsize);
691 * Allocate a handle for mapping from kva/uva/physical
692 * address space into bus device space.
695 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
700 *mapp = map = allocate_map(dmat, M_NOWAIT);
702 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
707 * Bouncing might be required if the driver asks for an exclusion
708 * region, a data alignment that is stricter than 1, or DMA that begins
709 * or ends with a partial cacheline. Whether bouncing will actually
710 * happen can't be known until mapping time, but we need to pre-allocate
711 * resources now because we might not be allowed to at mapping time.
713 error = allocate_bz_and_pages(dmat, map);
719 if (map->flags & DMAMAP_COHERENT)
720 atomic_add_32(&maps_coherent, 1);
721 atomic_add_32(&maps_total, 1);
728 * Destroy a handle for mapping from kva/uva/physical
729 * address space into bus device space.
732 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
735 if (STAILQ_FIRST(&map->bpages) != NULL || map->sync_count != 0) {
736 CTR3(KTR_BUSDMA, "%s: tag %p error %d",
737 __func__, dmat, EBUSY);
740 if (dmat->bounce_zone)
741 dmat->bounce_zone->map_count--;
742 if (map->flags & DMAMAP_COHERENT)
743 atomic_subtract_32(&maps_coherent, 1);
744 atomic_subtract_32(&maps_total, 1);
747 CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
752 * Allocate a piece of memory that can be efficiently mapped into bus device
753 * space based on the constraints listed in the dma tag. Returns a pointer to
754 * the allocated memory, and a pointer to an associated bus_dmamap.
757 bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
760 busdma_bufalloc_t ba;
761 struct busdma_bufzone *bufzone;
763 vm_memattr_t memattr;
766 if (flags & BUS_DMA_NOWAIT)
770 if (flags & BUS_DMA_ZERO)
773 *mapp = map = allocate_map(dmat, mflags);
775 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
776 __func__, dmat, dmat->flags, ENOMEM);
779 map->flags = DMAMAP_DMAMEM_ALLOC;
781 /* For coherent memory, set the map flag that disables sync ops. */
782 if (flags & BUS_DMA_COHERENT)
783 map->flags |= DMAMAP_COHERENT;
786 * Choose a busdma buffer allocator based on memory type flags.
787 * If the tag's COHERENT flag is set, that means normal memory
788 * is already coherent, use the normal allocator.
790 if ((flags & BUS_DMA_COHERENT) &&
791 ((dmat->flags & BUS_DMA_COHERENT) == 0)) {
792 memattr = VM_MEMATTR_UNCACHEABLE;
793 ba = coherent_allocator;
795 memattr = VM_MEMATTR_DEFAULT;
796 ba = standard_allocator;
800 * Try to find a bufzone in the allocator that holds a cache of buffers
801 * of the right size for this request. If the buffer is too big to be
802 * held in the allocator cache, this returns NULL.
804 bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
807 * Allocate the buffer from the uma(9) allocator if...
808 * - It's small enough to be in the allocator (bufzone not NULL).
809 * - The alignment constraint isn't larger than the allocation size
810 * (the allocator aligns buffers to their size boundaries).
811 * - There's no need to handle lowaddr/highaddr exclusion zones.
812 * else allocate non-contiguous pages if...
813 * - The page count that could get allocated doesn't exceed
814 * nsegments also when the maximum segment size is less
816 * - The alignment constraint isn't larger than a page boundary.
817 * - There are no boundary-crossing constraints.
818 * else allocate a block of contiguous pages because one or more of the
819 * constraints is something that only the contig allocator can fulfill.
821 if (bufzone != NULL && dmat->alignment <= bufzone->size &&
822 !exclusion_bounce(dmat)) {
823 *vaddr = uma_zalloc(bufzone->umazone, mflags);
824 } else if (dmat->nsegments >=
825 howmany(dmat->maxsize, MIN(dmat->maxsegsz, PAGE_SIZE)) &&
826 dmat->alignment <= PAGE_SIZE &&
827 (dmat->boundary % PAGE_SIZE) == 0) {
828 *vaddr = (void *)kmem_alloc_attr(dmat->maxsize, mflags, 0,
829 dmat->lowaddr, memattr);
831 *vaddr = (void *)kmem_alloc_contig(dmat->maxsize, mflags, 0,
832 dmat->lowaddr, dmat->alignment, dmat->boundary, memattr);
834 if (*vaddr == NULL) {
835 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
836 __func__, dmat, dmat->flags, ENOMEM);
841 if (map->flags & DMAMAP_COHERENT)
842 atomic_add_32(&maps_coherent, 1);
843 atomic_add_32(&maps_dmamem, 1);
844 atomic_add_32(&maps_total, 1);
847 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
848 __func__, dmat, dmat->flags, 0);
853 * Free a piece of memory that was allocated via bus_dmamem_alloc, along with
854 * its associated map.
857 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
859 struct busdma_bufzone *bufzone;
860 busdma_bufalloc_t ba;
862 if ((map->flags & DMAMAP_COHERENT) &&
863 ((dmat->flags & BUS_DMA_COHERENT) == 0))
864 ba = coherent_allocator;
866 ba = standard_allocator;
868 bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
870 if (bufzone != NULL && dmat->alignment <= bufzone->size &&
871 !exclusion_bounce(dmat))
872 uma_zfree(bufzone->umazone, vaddr);
874 kmem_free((vm_offset_t)vaddr, dmat->maxsize);
877 if (map->flags & DMAMAP_COHERENT)
878 atomic_subtract_32(&maps_coherent, 1);
879 atomic_subtract_32(&maps_total, 1);
880 atomic_subtract_32(&maps_dmamem, 1);
882 CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat, dmat->flags);
886 _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
887 bus_size_t buflen, int flags)
892 if (map->pagesneeded == 0) {
893 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
894 " map= %p, pagesneeded= %d",
895 dmat->lowaddr, dmat->boundary, dmat->alignment,
896 map, map->pagesneeded);
898 * Count the number of bounce pages
899 * needed in order to complete this transfer
902 while (buflen != 0) {
903 sgsize = MIN(buflen, dmat->maxsegsz);
904 if (must_bounce(dmat, map, curaddr, sgsize) != 0) {
906 PAGE_SIZE - (curaddr & PAGE_MASK));
912 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
917 _bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap, bus_dmamap_t map,
918 void *buf, bus_size_t buflen, int flags)
921 vm_offset_t vendaddr;
924 if (map->pagesneeded == 0) {
925 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
926 " map= %p, pagesneeded= %d",
927 dmat->lowaddr, dmat->boundary, dmat->alignment,
928 map, map->pagesneeded);
930 * Count the number of bounce pages
931 * needed in order to complete this transfer
933 vaddr = (vm_offset_t)buf;
934 vendaddr = (vm_offset_t)buf + buflen;
936 while (vaddr < vendaddr) {
937 if (__predict_true(pmap == kernel_pmap))
938 paddr = pmap_kextract(vaddr);
940 paddr = pmap_extract(pmap, vaddr);
941 if (must_bounce(dmat, map, paddr,
942 min(vendaddr - vaddr, (PAGE_SIZE - ((vm_offset_t)vaddr &
943 PAGE_MASK)))) != 0) {
946 vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
949 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
954 _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int flags)
957 /* Reserve Necessary Bounce Pages */
958 mtx_lock(&bounce_lock);
959 if (flags & BUS_DMA_NOWAIT) {
960 if (reserve_bounce_pages(dmat, map, 0) != 0) {
961 map->pagesneeded = 0;
962 mtx_unlock(&bounce_lock);
966 if (reserve_bounce_pages(dmat, map, 1) != 0) {
967 /* Queue us for resources */
968 STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
969 mtx_unlock(&bounce_lock);
970 return (EINPROGRESS);
973 mtx_unlock(&bounce_lock);
979 * Add a single contiguous physical range to the segment list.
982 _bus_dmamap_addseg(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t curaddr,
983 bus_size_t sgsize, bus_dma_segment_t *segs, int *segp)
985 bus_addr_t baddr, bmask;
989 * Make sure we don't cross any boundaries.
991 bmask = ~(dmat->boundary - 1);
992 if (dmat->boundary > 0) {
993 baddr = (curaddr + dmat->boundary) & bmask;
994 if (sgsize > (baddr - curaddr))
995 sgsize = (baddr - curaddr);
999 * Insert chunk into a segment, coalescing with
1000 * previous segment if possible.
1005 segs[seg].ds_addr = curaddr;
1006 segs[seg].ds_len = sgsize;
1008 if (curaddr == segs[seg].ds_addr + segs[seg].ds_len &&
1009 (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
1010 (dmat->boundary == 0 ||
1011 (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
1012 segs[seg].ds_len += sgsize;
1014 if (++seg >= dmat->nsegments)
1016 segs[seg].ds_addr = curaddr;
1017 segs[seg].ds_len = sgsize;
1025 * Utility function to load a physical buffer. segp contains
1026 * the starting segment on entrace, and the ending segment on exit.
1029 _bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
1030 bus_size_t buflen, int flags, bus_dma_segment_t *segs, int *segp)
1033 bus_addr_t sl_end = 0;
1035 struct sync_list *sl;
1039 segs = map->segments;
1041 counter_u64_add(maploads_total, 1);
1042 counter_u64_add(maploads_physmem, 1);
1044 if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1045 _bus_dmamap_count_phys(dmat, map, buf, buflen, flags);
1046 if (map->pagesneeded != 0) {
1047 counter_u64_add(maploads_bounced, 1);
1048 error = _bus_dmamap_reserve_pages(dmat, map, flags);
1054 sl = map->slist + map->sync_count - 1;
1056 while (buflen > 0) {
1058 sgsize = MIN(buflen, dmat->maxsegsz);
1059 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1061 sgsize = MIN(sgsize, PAGE_SIZE - (curaddr & PAGE_MASK));
1062 curaddr = add_bounce_page(dmat, map, 0, curaddr,
1064 } else if ((dmat->flags & BUS_DMA_COHERENT) == 0) {
1065 if (map->sync_count > 0)
1066 sl_end = sl->paddr + sl->datacount;
1068 if (map->sync_count == 0 || curaddr != sl_end) {
1069 if (++map->sync_count > dmat->nsegments)
1073 sl->paddr = curaddr;
1074 sl->datacount = sgsize;
1075 sl->pages = PHYS_TO_VM_PAGE(curaddr);
1076 KASSERT(sl->pages != NULL,
1077 ("%s: page at PA:0x%08lx is not in "
1078 "vm_page_array", __func__, curaddr));
1080 sl->datacount += sgsize;
1082 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1094 bus_dmamap_unload(dmat, map);
1095 return (EFBIG); /* XXX better return value here? */
1101 _bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map,
1102 struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
1103 bus_dma_segment_t *segs, int *segp)
1106 return (bus_dmamap_load_ma_triv(dmat, map, ma, tlen, ma_offs, flags,
1111 * Utility function to load a linear buffer. segp contains
1112 * the starting segment on entrance, and the ending segment on exit.
1115 _bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
1116 bus_size_t buflen, pmap_t pmap, int flags, bus_dma_segment_t *segs,
1121 bus_addr_t sl_pend = 0;
1122 vm_offset_t kvaddr, vaddr, sl_vend = 0;
1123 struct sync_list *sl;
1126 counter_u64_add(maploads_total, 1);
1127 if (map->flags & DMAMAP_COHERENT)
1128 counter_u64_add(maploads_coherent, 1);
1129 if (map->flags & DMAMAP_DMAMEM_ALLOC)
1130 counter_u64_add(maploads_dmamem, 1);
1133 segs = map->segments;
1135 if (flags & BUS_DMA_LOAD_MBUF) {
1136 counter_u64_add(maploads_mbuf, 1);
1137 map->flags |= DMAMAP_MBUF;
1140 if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1141 _bus_dmamap_count_pages(dmat, pmap, map, buf, buflen, flags);
1142 if (map->pagesneeded != 0) {
1143 counter_u64_add(maploads_bounced, 1);
1144 error = _bus_dmamap_reserve_pages(dmat, map, flags);
1150 sl = map->slist + map->sync_count - 1;
1151 vaddr = (vm_offset_t)buf;
1153 while (buflen > 0) {
1155 * Get the physical address for this segment.
1157 if (__predict_true(pmap == kernel_pmap)) {
1158 curaddr = pmap_kextract(vaddr);
1161 curaddr = pmap_extract(pmap, vaddr);
1166 * Compute the segment size, and adjust counts.
1168 sgsize = PAGE_SIZE - (curaddr & PAGE_MASK);
1169 if (sgsize > dmat->maxsegsz)
1170 sgsize = dmat->maxsegsz;
1171 if (buflen < sgsize)
1174 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1176 curaddr = add_bounce_page(dmat, map, kvaddr, curaddr,
1178 } else if ((dmat->flags & BUS_DMA_COHERENT) == 0) {
1179 if (map->sync_count > 0) {
1180 sl_pend = sl->paddr + sl->datacount;
1181 sl_vend = sl->vaddr + sl->datacount;
1184 if (map->sync_count == 0 ||
1185 (kvaddr != 0 && kvaddr != sl_vend) ||
1186 (curaddr != sl_pend)) {
1188 if (++map->sync_count > dmat->nsegments)
1192 sl->paddr = curaddr;
1196 sl->pages = PHYS_TO_VM_PAGE(curaddr);
1197 KASSERT(sl->pages != NULL,
1198 ("%s: page at PA:0x%08lx is not "
1199 "in vm_page_array", __func__,
1202 sl->datacount = sgsize;
1204 sl->datacount += sgsize;
1206 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1219 bus_dmamap_unload(dmat, map);
1220 return (EFBIG); /* XXX better return value here? */
1226 _bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map, struct memdesc *mem,
1227 bus_dmamap_callback_t *callback, void *callback_arg)
1232 map->callback = callback;
1233 map->callback_arg = callback_arg;
1237 _bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map,
1238 bus_dma_segment_t *segs, int nsegs, int error)
1242 segs = map->segments;
1247 * Release the mapping held by map.
1250 bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1252 struct bounce_page *bpage;
1253 struct bounce_zone *bz;
1255 if ((bz = dmat->bounce_zone) != NULL) {
1256 while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1257 STAILQ_REMOVE_HEAD(&map->bpages, links);
1258 free_bounce_page(dmat, bpage);
1261 bz = dmat->bounce_zone;
1262 bz->free_bpages += map->pagesreserved;
1263 bz->reserved_bpages -= map->pagesreserved;
1264 map->pagesreserved = 0;
1265 map->pagesneeded = 0;
1267 map->sync_count = 0;
1268 map->flags &= ~DMAMAP_MBUF;
1272 dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size)
1275 * Write back any partial cachelines immediately before and
1276 * after the DMA region. We don't need to round the address
1277 * down to the nearest cacheline or specify the exact size,
1278 * as dcache_wb_poc() will do the rounding for us and works
1279 * at cacheline granularity.
1281 if (va & BUSDMA_DCACHE_MASK)
1282 dcache_wb_poc(va, pa, 1);
1283 if ((va + size) & BUSDMA_DCACHE_MASK)
1284 dcache_wb_poc(va + size, pa + size, 1);
1286 dcache_inv_poc_dma(va, pa, size);
1290 dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op)
1292 uint32_t len, offset;
1295 vm_offset_t va, tempva;
1298 offset = sl->paddr & PAGE_MASK;
1300 size = sl->datacount;
1303 for ( ; size != 0; size -= len, pa += len, offset = 0, ++m) {
1305 if (sl->vaddr == 0) {
1306 len = min(PAGE_SIZE - offset, size);
1307 tempva = pmap_quick_enter_page(m);
1308 va = tempva | offset;
1309 KASSERT(pa == (VM_PAGE_TO_PHYS(m) | offset),
1310 ("unexpected vm_page_t phys: 0x%08x != 0x%08x",
1311 VM_PAGE_TO_PHYS(m) | offset, pa));
1313 len = sl->datacount;
1318 case BUS_DMASYNC_PREWRITE:
1319 case BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD:
1320 dcache_wb_poc(va, pa, len);
1322 case BUS_DMASYNC_PREREAD:
1324 * An mbuf may start in the middle of a cacheline. There
1325 * will be no cpu writes to the beginning of that line
1326 * (which contains the mbuf header) while dma is in
1327 * progress. Handle that case by doing a writeback of
1328 * just the first cacheline before invalidating the
1329 * overall buffer. Any mbuf in a chain may have this
1330 * misalignment. Buffers which are not mbufs bounce if
1331 * they are not aligned to a cacheline.
1333 dma_preread_safe(va, pa, len);
1335 case BUS_DMASYNC_POSTREAD:
1336 case BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE:
1337 dcache_inv_poc(va, pa, len);
1340 panic("unsupported combination of sync operations: "
1345 pmap_quick_remove_page(tempva);
1350 bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1352 struct bounce_page *bpage;
1353 struct sync_list *sl, *end;
1354 vm_offset_t datavaddr, tempvaddr;
1356 if (op == BUS_DMASYNC_POSTWRITE)
1360 * If the buffer was from user space, it is possible that this is not
1361 * the same vm map, especially on a POST operation. It's not clear that
1362 * dma on userland buffers can work at all right now. To be safe, until
1363 * we're able to test direct userland dma, panic on a map mismatch.
1365 if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1367 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1368 "performing bounce", __func__, dmat, dmat->flags, op);
1371 * For PREWRITE do a writeback. Clean the caches from the
1372 * innermost to the outermost levels.
1374 if (op & BUS_DMASYNC_PREWRITE) {
1375 while (bpage != NULL) {
1377 datavaddr = bpage->datavaddr;
1378 if (datavaddr == 0) {
1379 tempvaddr = pmap_quick_enter_page(
1381 datavaddr = tempvaddr | bpage->dataoffs;
1383 bcopy((void *)datavaddr, (void *)bpage->vaddr,
1386 pmap_quick_remove_page(tempvaddr);
1387 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1388 dcache_wb_poc(bpage->vaddr,
1389 bpage->busaddr, bpage->datacount);
1390 bpage = STAILQ_NEXT(bpage, links);
1392 dmat->bounce_zone->total_bounced++;
1396 * Do an invalidate for PREREAD unless a writeback was already
1397 * done above due to PREWRITE also being set. The reason for a
1398 * PREREAD invalidate is to prevent dirty lines currently in the
1399 * cache from being evicted during the DMA. If a writeback was
1400 * done due to PREWRITE also being set there will be no dirty
1401 * lines and the POSTREAD invalidate handles the rest. The
1402 * invalidate is done from the innermost to outermost level. If
1403 * L2 were done first, a dirty cacheline could be automatically
1404 * evicted from L1 before we invalidated it, re-dirtying the L2.
1406 if ((op & BUS_DMASYNC_PREREAD) && !(op & BUS_DMASYNC_PREWRITE)) {
1407 bpage = STAILQ_FIRST(&map->bpages);
1408 while (bpage != NULL) {
1409 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1410 dcache_inv_poc_dma(bpage->vaddr,
1411 bpage->busaddr, bpage->datacount);
1412 bpage = STAILQ_NEXT(bpage, links);
1417 * Re-invalidate the caches on a POSTREAD, even though they were
1418 * already invalidated at PREREAD time. Aggressive prefetching
1419 * due to accesses to other data near the dma buffer could have
1420 * brought buffer data into the caches which is now stale. The
1421 * caches are invalidated from the outermost to innermost; the
1422 * prefetches could be happening right now, and if L1 were
1423 * invalidated first, stale L2 data could be prefetched into L1.
1425 if (op & BUS_DMASYNC_POSTREAD) {
1426 while (bpage != NULL) {
1427 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1428 dcache_inv_poc(bpage->vaddr,
1429 bpage->busaddr, bpage->datacount);
1431 datavaddr = bpage->datavaddr;
1432 if (datavaddr == 0) {
1433 tempvaddr = pmap_quick_enter_page(
1435 datavaddr = tempvaddr | bpage->dataoffs;
1437 bcopy((void *)bpage->vaddr, (void *)datavaddr,
1440 pmap_quick_remove_page(tempvaddr);
1441 bpage = STAILQ_NEXT(bpage, links);
1443 dmat->bounce_zone->total_bounced++;
1448 * For COHERENT memory no cache maintenance is necessary, but ensure all
1449 * writes have reached memory for the PREWRITE case. No action is
1450 * needed for a PREREAD without PREWRITE also set, because that would
1451 * imply that the cpu had written to the COHERENT buffer and expected
1452 * the dma device to see that change, and by definition a PREWRITE sync
1453 * is required to make that happen.
1455 if (map->flags & DMAMAP_COHERENT) {
1456 if (op & BUS_DMASYNC_PREWRITE) {
1458 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1459 cpu_l2cache_drain_writebuf();
1465 * Cache maintenance for normal (non-COHERENT non-bounce) buffers. All
1466 * the comments about the sequences for flushing cache levels in the
1467 * bounce buffer code above apply here as well. In particular, the fact
1468 * that the sequence is inner-to-outer for PREREAD invalidation and
1469 * outer-to-inner for POSTREAD invalidation is not a mistake.
1471 if (map->sync_count != 0) {
1472 sl = &map->slist[0];
1473 end = &map->slist[map->sync_count];
1474 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1475 "performing sync", __func__, dmat, dmat->flags, op);
1477 for ( ; sl != end; ++sl)
1478 dma_dcache_sync(sl, op);
1483 init_bounce_pages(void *dummy __unused)
1487 STAILQ_INIT(&bounce_zone_list);
1488 STAILQ_INIT(&bounce_map_waitinglist);
1489 STAILQ_INIT(&bounce_map_callbacklist);
1490 mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
1492 SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
1494 static struct sysctl_ctx_list *
1495 busdma_sysctl_tree(struct bounce_zone *bz)
1498 return (&bz->sysctl_tree);
1501 static struct sysctl_oid *
1502 busdma_sysctl_tree_top(struct bounce_zone *bz)
1505 return (bz->sysctl_tree_top);
1509 alloc_bounce_zone(bus_dma_tag_t dmat)
1511 struct bounce_zone *bz;
1513 /* Check to see if we already have a suitable zone */
1514 STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1515 if ((dmat->alignment <= bz->alignment) &&
1516 (dmat->lowaddr >= bz->lowaddr)) {
1517 dmat->bounce_zone = bz;
1522 if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_BUSDMA,
1523 M_NOWAIT | M_ZERO)) == NULL)
1526 STAILQ_INIT(&bz->bounce_page_list);
1527 bz->free_bpages = 0;
1528 bz->reserved_bpages = 0;
1529 bz->active_bpages = 0;
1530 bz->lowaddr = dmat->lowaddr;
1531 bz->alignment = MAX(dmat->alignment, PAGE_SIZE);
1533 snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1535 snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1536 STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1537 dmat->bounce_zone = bz;
1539 sysctl_ctx_init(&bz->sysctl_tree);
1540 bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
1541 SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1543 if (bz->sysctl_tree_top == NULL) {
1544 sysctl_ctx_free(&bz->sysctl_tree);
1545 return (0); /* XXX error code? */
1548 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1549 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1550 "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1551 "Total bounce pages");
1552 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1553 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1554 "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1555 "Free bounce pages");
1556 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1557 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1558 "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1559 "Reserved bounce pages");
1560 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1561 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1562 "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1563 "Active bounce pages");
1564 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1565 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1566 "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1567 "Total bounce requests (pages bounced)");
1568 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1569 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1570 "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1571 "Total bounce requests that were deferred");
1572 SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1573 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1574 "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1575 SYSCTL_ADD_ULONG(busdma_sysctl_tree(bz),
1576 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1577 "alignment", CTLFLAG_RD, &bz->alignment, "");
1583 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1585 struct bounce_zone *bz;
1588 bz = dmat->bounce_zone;
1590 while (numpages > 0) {
1591 struct bounce_page *bpage;
1593 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_BUSDMA,
1598 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_BOUNCE,
1599 M_NOWAIT, 0ul, bz->lowaddr, PAGE_SIZE, 0);
1600 if (bpage->vaddr == 0) {
1601 free(bpage, M_BUSDMA);
1604 bpage->busaddr = pmap_kextract(bpage->vaddr);
1605 mtx_lock(&bounce_lock);
1606 STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1610 mtx_unlock(&bounce_lock);
1618 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1620 struct bounce_zone *bz;
1623 mtx_assert(&bounce_lock, MA_OWNED);
1624 bz = dmat->bounce_zone;
1625 pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1626 if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1627 return (map->pagesneeded - (map->pagesreserved + pages));
1628 bz->free_bpages -= pages;
1629 bz->reserved_bpages += pages;
1630 map->pagesreserved += pages;
1631 pages = map->pagesneeded - map->pagesreserved;
1637 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1638 bus_addr_t addr, bus_size_t size)
1640 struct bounce_zone *bz;
1641 struct bounce_page *bpage;
1643 KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1644 KASSERT(map != NULL, ("add_bounce_page: bad map %p", map));
1646 bz = dmat->bounce_zone;
1647 if (map->pagesneeded == 0)
1648 panic("add_bounce_page: map doesn't need any pages");
1651 if (map->pagesreserved == 0)
1652 panic("add_bounce_page: map doesn't need any pages");
1653 map->pagesreserved--;
1655 mtx_lock(&bounce_lock);
1656 bpage = STAILQ_FIRST(&bz->bounce_page_list);
1658 panic("add_bounce_page: free page list is empty");
1660 STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1661 bz->reserved_bpages--;
1662 bz->active_bpages++;
1663 mtx_unlock(&bounce_lock);
1665 if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1666 /* Page offset needs to be preserved. */
1667 bpage->vaddr |= addr & PAGE_MASK;
1668 bpage->busaddr |= addr & PAGE_MASK;
1670 bpage->datavaddr = vaddr;
1671 bpage->datapage = PHYS_TO_VM_PAGE(addr);
1672 bpage->dataoffs = addr & PAGE_MASK;
1673 bpage->datacount = size;
1674 STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1675 return (bpage->busaddr);
1679 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1681 struct bus_dmamap *map;
1682 struct bounce_zone *bz;
1684 bz = dmat->bounce_zone;
1685 bpage->datavaddr = 0;
1686 bpage->datacount = 0;
1687 if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1689 * Reset the bounce page to start at offset 0. Other uses
1690 * of this bounce page may need to store a full page of
1691 * data and/or assume it starts on a page boundary.
1693 bpage->vaddr &= ~PAGE_MASK;
1694 bpage->busaddr &= ~PAGE_MASK;
1697 mtx_lock(&bounce_lock);
1698 STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1700 bz->active_bpages--;
1701 if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1702 if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1703 STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1704 STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1706 busdma_swi_pending = 1;
1707 bz->total_deferred++;
1708 swi_sched(vm_ih, 0);
1711 mtx_unlock(&bounce_lock);
1718 struct bus_dmamap *map;
1720 mtx_lock(&bounce_lock);
1721 while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1722 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1723 mtx_unlock(&bounce_lock);
1725 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_LOCK);
1726 bus_dmamap_load_mem(map->dmat, map, &map->mem, map->callback,
1727 map->callback_arg, BUS_DMA_WAITOK);
1728 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_UNLOCK);
1729 mtx_lock(&bounce_lock);
1731 mtx_unlock(&bounce_lock);