2 * Copyright (c) 1997, 1998 Justin T. Gibbs.
3 * Copyright (c) 2015-2016 The FreeBSD Foundation
6 * Portions of this software were developed by Andrew Turner
7 * under sponsorship of the FreeBSD Foundation.
9 * Portions of this software were developed by Semihalf
10 * under sponsorship of the FreeBSD Foundation.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions, and the following disclaimer,
17 * without modification, immediately at the beginning of the file.
18 * 2. The name of the author may not be used to endorse or promote products
19 * derived from this software without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
25 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/malloc.h>
41 #include <sys/interrupt.h>
42 #include <sys/kernel.h>
46 #include <sys/memdesc.h>
47 #include <sys/mutex.h>
48 #include <sys/sysctl.h>
52 #include <vm/vm_extern.h>
53 #include <vm/vm_kern.h>
54 #include <vm/vm_page.h>
55 #include <vm/vm_map.h>
57 #include <machine/atomic.h>
58 #include <machine/bus.h>
59 #include <machine/md_var.h>
60 #include <arm64/include/bus_dma_impl.h>
62 #define MAX_BPAGES 4096
65 BF_COULD_BOUNCE = 0x01,
66 BF_MIN_ALLOC_COMP = 0x02,
74 struct bus_dma_tag_common common;
76 size_t alloc_alignment;
79 bus_dma_segment_t *segments;
80 struct bounce_zone *bounce_zone;
84 vm_offset_t vaddr; /* kva of bounce buffer */
85 bus_addr_t busaddr; /* Physical address */
86 vm_offset_t datavaddr; /* kva of client data */
87 vm_page_t datapage; /* physical page of client data */
88 vm_offset_t dataoffs; /* page offset of client data */
89 bus_size_t datacount; /* client data count */
90 STAILQ_ENTRY(bounce_page) links;
93 int busdma_swi_pending;
96 STAILQ_ENTRY(bounce_zone) links;
97 STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
105 bus_size_t alignment;
109 struct sysctl_ctx_list sysctl_tree;
110 struct sysctl_oid *sysctl_tree_top;
113 static struct mtx bounce_lock;
114 static int total_bpages;
115 static int busdma_zonecount;
116 static STAILQ_HEAD(, bounce_zone) bounce_zone_list;
118 static SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
119 "Busdma parameters");
120 SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bpages, 0,
121 "Total bounce pages");
124 vm_offset_t vaddr; /* kva of client data */
125 bus_addr_t paddr; /* physical address */
126 vm_page_t pages; /* starting page of client data */
127 bus_size_t datacount; /* client data count */
131 struct bp_list bpages;
136 bus_dmamap_callback_t *callback;
138 STAILQ_ENTRY(bus_dmamap) links;
140 #define DMAMAP_COHERENT (1 << 0)
141 #define DMAMAP_FROM_DMAMEM (1 << 1)
142 #define DMAMAP_MBUF (1 << 2)
144 struct sync_list slist[];
147 static STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
148 static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist;
150 static void init_bounce_pages(void *dummy);
151 static int alloc_bounce_zone(bus_dma_tag_t dmat);
152 static int alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages);
153 static int reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
155 static bus_addr_t add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map,
156 vm_offset_t vaddr, bus_addr_t addr, bus_size_t size);
157 static void free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage);
158 int run_filter(bus_dma_tag_t dmat, bus_addr_t paddr);
159 static bool _bus_dmamap_pagesneeded(bus_dma_tag_t dmat, bus_dmamap_t map,
160 vm_paddr_t buf, bus_size_t buflen, int *pagesneeded);
161 static void _bus_dmamap_count_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
162 pmap_t pmap, void *buf, bus_size_t buflen, int flags);
163 static void _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map,
164 vm_paddr_t buf, bus_size_t buflen, int flags);
165 static int _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
169 * Return true if the DMA should bounce because the start or end does not fall
170 * on a cacheline boundary (which would require a partial cacheline flush).
171 * COHERENT memory doesn't trigger cacheline flushes. Memory allocated by
172 * bus_dmamem_alloc() is always aligned to cacheline boundaries, and there's a
173 * strict rule that such memory cannot be accessed by the CPU while DMA is in
174 * progress (or by multiple DMA engines at once), so that it's always safe to do
175 * full cacheline flushes even if that affects memory outside the range of a
176 * given DMA operation that doesn't involve the full allocated buffer. If we're
177 * mapping an mbuf, that follows the same rules as a buffer we allocated.
180 cacheline_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t paddr,
184 #define DMAMAP_CACHELINE_FLAGS \
185 (DMAMAP_FROM_DMAMEM | DMAMAP_COHERENT | DMAMAP_MBUF)
186 if ((dmat->bounce_flags & BF_COHERENT) != 0)
188 if (map != NULL && (map->flags & DMAMAP_CACHELINE_FLAGS) != 0)
190 return (((paddr | size) & (dcache_line_size - 1)) != 0);
191 #undef DMAMAP_CACHELINE_FLAGS
195 * Return true if the given address does not fall on the alignment boundary.
198 alignment_bounce(bus_dma_tag_t dmat, bus_addr_t addr)
201 return ((addr & (dmat->common.alignment - 1)) != 0);
205 might_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t paddr,
209 /* Memory allocated by bounce_bus_dmamem_alloc won't bounce */
210 if (map && (map->flags & DMAMAP_FROM_DMAMEM) != 0)
213 if ((dmat->bounce_flags & BF_COULD_BOUNCE) != 0)
216 if (cacheline_bounce(dmat, map, paddr, size))
219 if (alignment_bounce(dmat, paddr))
226 must_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t paddr,
230 if (cacheline_bounce(dmat, map, paddr, size))
233 if (alignment_bounce(dmat, paddr))
236 if ((dmat->bounce_flags & BF_COULD_BOUNCE) != 0 &&
237 bus_dma_run_filter(&dmat->common, paddr))
244 * Allocate a device specific dma_tag.
247 bounce_bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
248 bus_addr_t boundary, bus_addr_t lowaddr, bus_addr_t highaddr,
249 bus_dma_filter_t *filter, void *filterarg, bus_size_t maxsize,
250 int nsegments, bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
251 void *lockfuncarg, bus_dma_tag_t *dmat)
253 bus_dma_tag_t newtag;
257 error = common_bus_dma_tag_create(parent != NULL ? &parent->common :
258 NULL, alignment, boundary, lowaddr, highaddr, filter, filterarg,
259 maxsize, nsegments, maxsegsz, flags, lockfunc, lockfuncarg,
260 sizeof (struct bus_dma_tag), (void **)&newtag);
264 newtag->common.impl = &bus_dma_bounce_impl;
265 newtag->map_count = 0;
266 newtag->segments = NULL;
268 if ((flags & BUS_DMA_COHERENT) != 0) {
269 newtag->bounce_flags |= BF_COHERENT;
270 newtag->alloc_alignment = newtag->common.alignment;
271 newtag->alloc_size = newtag->common.maxsize;
274 * Ensure the buffer is aligned to a cacheline when allocating
275 * a non-coherent buffer. This is so we don't have any data
276 * that another CPU may be accessing around DMA buffer
277 * causing the cache to become dirty.
279 newtag->alloc_alignment = MAX(newtag->common.alignment,
281 newtag->alloc_size = roundup2(newtag->common.maxsize,
285 if (parent != NULL) {
286 if ((newtag->common.filter != NULL ||
287 (parent->bounce_flags & BF_COULD_BOUNCE) != 0))
288 newtag->bounce_flags |= BF_COULD_BOUNCE;
290 /* Copy some flags from the parent */
291 newtag->bounce_flags |= parent->bounce_flags & BF_COHERENT;
294 if (newtag->common.lowaddr < ptoa((vm_paddr_t)Maxmem) ||
295 newtag->common.alignment > 1)
296 newtag->bounce_flags |= BF_COULD_BOUNCE;
298 if ((flags & BUS_DMA_ALLOCNOW) != 0) {
299 struct bounce_zone *bz;
301 * Round size up to a full page, and add one more page because
302 * there can always be one more boundary crossing than the
303 * number of pages in a transfer.
305 maxsize = roundup2(maxsize, PAGE_SIZE) + PAGE_SIZE;
308 if ((error = alloc_bounce_zone(newtag)) != 0) {
309 free(newtag, M_DEVBUF);
312 bz = newtag->bounce_zone;
314 if (ptoa(bz->total_bpages) < maxsize) {
317 pages = atop(maxsize) + 1 - bz->total_bpages;
319 /* Add pages to our bounce pool */
320 if (alloc_bounce_pages(newtag, pages) < pages)
323 /* Performed initial allocation */
324 newtag->bounce_flags |= BF_MIN_ALLOC_COMP;
329 free(newtag, M_DEVBUF);
332 CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
333 __func__, newtag, (newtag != NULL ? newtag->common.flags : 0),
339 bounce_bus_dma_tag_destroy(bus_dma_tag_t dmat)
341 bus_dma_tag_t dmat_copy, parent;
348 if (dmat->map_count != 0) {
352 while (dmat != NULL) {
353 parent = (bus_dma_tag_t)dmat->common.parent;
354 atomic_subtract_int(&dmat->common.ref_count, 1);
355 if (dmat->common.ref_count == 0) {
356 if (dmat->segments != NULL)
357 free(dmat->segments, M_DEVBUF);
358 free(dmat, M_DEVBUF);
360 * Last reference count, so
361 * release our reference
362 * count on our parent.
370 CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
375 bounce_bus_dma_id_mapped(bus_dma_tag_t dmat, vm_paddr_t buf, bus_size_t buflen)
378 if (!might_bounce(dmat, NULL, buf, buflen))
380 return (!_bus_dmamap_pagesneeded(dmat, NULL, buf, buflen, NULL));
384 alloc_dmamap(bus_dma_tag_t dmat, int flags)
389 mapsize = sizeof(*map);
390 mapsize += sizeof(struct sync_list) * dmat->common.nsegments;
391 map = malloc(mapsize, M_DEVBUF, flags | M_ZERO);
395 /* Initialize the new map */
396 STAILQ_INIT(&map->bpages);
402 * Allocate a handle for mapping from kva/uva/physical
403 * address space into bus device space.
406 bounce_bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
408 struct bounce_zone *bz;
409 int error, maxpages, pages;
413 if (dmat->segments == NULL) {
414 dmat->segments = (bus_dma_segment_t *)malloc(
415 sizeof(bus_dma_segment_t) * dmat->common.nsegments,
417 if (dmat->segments == NULL) {
418 CTR3(KTR_BUSDMA, "%s: tag %p error %d",
419 __func__, dmat, ENOMEM);
424 *mapp = alloc_dmamap(dmat, M_NOWAIT);
426 CTR3(KTR_BUSDMA, "%s: tag %p error %d",
427 __func__, dmat, ENOMEM);
432 * Bouncing might be required if the driver asks for an active
433 * exclusion region, a data alignment that is stricter than 1, and/or
434 * an active address boundary.
436 if (dmat->bounce_zone == NULL) {
437 if ((error = alloc_bounce_zone(dmat)) != 0) {
438 free(*mapp, M_DEVBUF);
442 bz = dmat->bounce_zone;
445 * Attempt to add pages to our pool on a per-instance basis up to a sane
446 * limit. Even if the tag isn't subject of bouncing due to alignment
447 * and boundary constraints, it could still auto-bounce due to
448 * cacheline alignment, which requires at most two bounce pages.
450 if (dmat->common.alignment > 1)
451 maxpages = MAX_BPAGES;
453 maxpages = MIN(MAX_BPAGES, Maxmem -
454 atop(dmat->common.lowaddr));
455 if ((dmat->bounce_flags & BF_MIN_ALLOC_COMP) == 0 ||
456 (bz->map_count > 0 && bz->total_bpages < maxpages)) {
457 pages = atop(roundup2(dmat->common.maxsize, PAGE_SIZE)) + 1;
458 pages = MIN(maxpages - bz->total_bpages, pages);
459 pages = MAX(pages, 2);
460 if (alloc_bounce_pages(dmat, pages) < pages)
462 if ((dmat->bounce_flags & BF_MIN_ALLOC_COMP) == 0) {
464 dmat->bounce_flags |= BF_MIN_ALLOC_COMP;
473 if ((dmat->bounce_flags & BF_COHERENT) != 0)
474 (*mapp)->flags |= DMAMAP_COHERENT;
476 free(*mapp, M_DEVBUF);
478 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
479 __func__, dmat, dmat->common.flags, error);
484 * Destroy a handle for mapping from kva/uva/physical
485 * address space into bus device space.
488 bounce_bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
491 /* Check we are destroying the correct map type */
492 if ((map->flags & DMAMAP_FROM_DMAMEM) != 0)
493 panic("bounce_bus_dmamap_destroy: Invalid map freed\n");
495 if (STAILQ_FIRST(&map->bpages) != NULL || map->sync_count != 0) {
496 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, EBUSY);
499 if (dmat->bounce_zone)
500 dmat->bounce_zone->map_count--;
503 CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
508 * Allocate a piece of memory that can be efficiently mapped into
509 * bus device space based on the constraints lited in the dma tag.
510 * A dmamap to for use with dmamap_load is also allocated.
513 bounce_bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
519 if (flags & BUS_DMA_NOWAIT)
524 if (dmat->segments == NULL) {
525 dmat->segments = (bus_dma_segment_t *)malloc(
526 sizeof(bus_dma_segment_t) * dmat->common.nsegments,
528 if (dmat->segments == NULL) {
529 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
530 __func__, dmat, dmat->common.flags, ENOMEM);
534 if (flags & BUS_DMA_ZERO)
536 if (flags & BUS_DMA_NOCACHE)
537 attr = VM_MEMATTR_UNCACHEABLE;
538 else if ((flags & BUS_DMA_COHERENT) != 0 &&
539 (dmat->bounce_flags & BF_COHERENT) == 0)
541 * If we have a non-coherent tag, and are trying to allocate
542 * a coherent block of memory it needs to be uncached.
544 attr = VM_MEMATTR_UNCACHEABLE;
546 attr = VM_MEMATTR_DEFAULT;
549 * Create the map, but don't set the could bounce flag as
550 * this allocation should never bounce;
552 *mapp = alloc_dmamap(dmat, mflags);
554 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
555 __func__, dmat, dmat->common.flags, ENOMEM);
560 * Mark the map as coherent if we used uncacheable memory or the
561 * tag was already marked as coherent.
563 if (attr == VM_MEMATTR_UNCACHEABLE ||
564 (dmat->bounce_flags & BF_COHERENT) != 0)
565 (*mapp)->flags |= DMAMAP_COHERENT;
567 (*mapp)->flags |= DMAMAP_FROM_DMAMEM;
570 * Allocate the buffer from the malloc(9) allocator if...
571 * - It's small enough to fit into a single power of two sized bucket.
572 * - The alignment is less than or equal to the maximum size
573 * - The low address requirement is fulfilled.
574 * else allocate non-contiguous pages if...
575 * - The page count that could get allocated doesn't exceed
576 * nsegments also when the maximum segment size is less
578 * - The alignment constraint isn't larger than a page boundary.
579 * - There are no boundary-crossing constraints.
580 * else allocate a block of contiguous pages because one or more of the
581 * constraints is something that only the contig allocator can fulfill.
583 * NOTE: The (dmat->common.alignment <= dmat->maxsize) check
584 * below is just a quick hack. The exact alignment guarantees
585 * of malloc(9) need to be nailed down, and the code below
586 * should be rewritten to take that into account.
588 * In the meantime warn the user if malloc gets it wrong.
590 if ((dmat->alloc_size <= PAGE_SIZE) &&
591 (dmat->alloc_alignment <= dmat->alloc_size) &&
592 dmat->common.lowaddr >= ptoa((vm_paddr_t)Maxmem) &&
593 attr == VM_MEMATTR_DEFAULT) {
594 *vaddr = malloc(dmat->alloc_size, M_DEVBUF, mflags);
595 } else if (dmat->common.nsegments >=
596 howmany(dmat->alloc_size, MIN(dmat->common.maxsegsz, PAGE_SIZE)) &&
597 dmat->alloc_alignment <= PAGE_SIZE &&
598 (dmat->common.boundary % PAGE_SIZE) == 0) {
599 /* Page-based multi-segment allocations allowed */
600 *vaddr = (void *)kmem_alloc_attr(dmat->alloc_size, mflags,
601 0ul, dmat->common.lowaddr, attr);
602 dmat->bounce_flags |= BF_KMEM_ALLOC;
604 *vaddr = (void *)kmem_alloc_contig(dmat->alloc_size, mflags,
605 0ul, dmat->common.lowaddr, dmat->alloc_alignment != 0 ?
606 dmat->alloc_alignment : 1ul, dmat->common.boundary, attr);
607 dmat->bounce_flags |= BF_KMEM_ALLOC;
609 if (*vaddr == NULL) {
610 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
611 __func__, dmat, dmat->common.flags, ENOMEM);
612 free(*mapp, M_DEVBUF);
614 } else if (vtophys(*vaddr) & (dmat->alloc_alignment - 1)) {
615 printf("bus_dmamem_alloc failed to align memory properly.\n");
618 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
619 __func__, dmat, dmat->common.flags, 0);
624 * Free a piece of memory and it's allociated dmamap, that was allocated
625 * via bus_dmamem_alloc. Make the same choice for free/contigfree.
628 bounce_bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
632 * Check the map came from bounce_bus_dmamem_alloc, so the map
633 * should be NULL and the BF_KMEM_ALLOC flag cleared if malloc()
634 * was used and set if kmem_alloc_contig() was used.
636 if ((map->flags & DMAMAP_FROM_DMAMEM) == 0)
637 panic("bus_dmamem_free: Invalid map freed\n");
638 if ((dmat->bounce_flags & BF_KMEM_ALLOC) == 0)
639 free(vaddr, M_DEVBUF);
641 kmem_free((vm_offset_t)vaddr, dmat->alloc_size);
644 CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat,
649 _bus_dmamap_pagesneeded(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
650 bus_size_t buflen, int *pagesneeded)
657 * Count the number of bounce pages needed in order to
658 * complete this transfer
662 while (buflen != 0) {
663 sgsize = MIN(buflen, dmat->common.maxsegsz);
664 if (must_bounce(dmat, map, curaddr, sgsize)) {
666 PAGE_SIZE - (curaddr & PAGE_MASK));
667 if (pagesneeded == NULL)
675 if (pagesneeded != NULL)
676 *pagesneeded = count;
681 _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
682 bus_size_t buflen, int flags)
685 if (map->pagesneeded == 0) {
686 _bus_dmamap_pagesneeded(dmat, map, buf, buflen,
688 CTR1(KTR_BUSDMA, "pagesneeded= %d\n", map->pagesneeded);
693 _bus_dmamap_count_pages(bus_dma_tag_t dmat, bus_dmamap_t map, pmap_t pmap,
694 void *buf, bus_size_t buflen, int flags)
697 vm_offset_t vendaddr;
701 if (map->pagesneeded == 0) {
702 CTR4(KTR_BUSDMA, "lowaddr= %d Maxmem= %d, boundary= %d, "
703 "alignment= %d", dmat->common.lowaddr,
704 ptoa((vm_paddr_t)Maxmem),
705 dmat->common.boundary, dmat->common.alignment);
706 CTR2(KTR_BUSDMA, "map= %p, pagesneeded= %d", map,
709 * Count the number of bounce pages
710 * needed in order to complete this transfer
712 vaddr = (vm_offset_t)buf;
713 vendaddr = (vm_offset_t)buf + buflen;
715 while (vaddr < vendaddr) {
716 sg_len = PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK);
717 if (pmap == kernel_pmap)
718 paddr = pmap_kextract(vaddr);
720 paddr = pmap_extract(pmap, vaddr);
721 if (must_bounce(dmat, map, paddr,
722 min(vendaddr - vaddr, (PAGE_SIZE - ((vm_offset_t)vaddr &
723 PAGE_MASK)))) != 0) {
724 sg_len = roundup2(sg_len,
725 dmat->common.alignment);
730 CTR1(KTR_BUSDMA, "pagesneeded= %d\n", map->pagesneeded);
735 _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int flags)
738 /* Reserve Necessary Bounce Pages */
739 mtx_lock(&bounce_lock);
740 if (flags & BUS_DMA_NOWAIT) {
741 if (reserve_bounce_pages(dmat, map, 0) != 0) {
742 mtx_unlock(&bounce_lock);
746 if (reserve_bounce_pages(dmat, map, 1) != 0) {
747 /* Queue us for resources */
748 STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
749 mtx_unlock(&bounce_lock);
750 return (EINPROGRESS);
753 mtx_unlock(&bounce_lock);
759 * Add a single contiguous physical range to the segment list.
762 _bus_dmamap_addseg(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t curaddr,
763 bus_size_t sgsize, bus_dma_segment_t *segs, int *segp)
765 bus_addr_t baddr, bmask;
769 * Make sure we don't cross any boundaries.
771 bmask = ~(dmat->common.boundary - 1);
772 if (dmat->common.boundary > 0) {
773 baddr = (curaddr + dmat->common.boundary) & bmask;
774 if (sgsize > (baddr - curaddr))
775 sgsize = (baddr - curaddr);
779 * Insert chunk into a segment, coalescing with
780 * previous segment if possible.
785 segs[seg].ds_addr = curaddr;
786 segs[seg].ds_len = sgsize;
788 if (curaddr == segs[seg].ds_addr + segs[seg].ds_len &&
789 (segs[seg].ds_len + sgsize) <= dmat->common.maxsegsz &&
790 (dmat->common.boundary == 0 ||
791 (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
792 segs[seg].ds_len += sgsize;
794 if (++seg >= dmat->common.nsegments)
796 segs[seg].ds_addr = curaddr;
797 segs[seg].ds_len = sgsize;
805 * Utility function to load a physical buffer. segp contains
806 * the starting segment on entrace, and the ending segment on exit.
809 bounce_bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map,
810 vm_paddr_t buf, bus_size_t buflen, int flags, bus_dma_segment_t *segs,
813 struct sync_list *sl;
815 bus_addr_t curaddr, sl_end;
819 segs = dmat->segments;
821 if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
822 _bus_dmamap_count_phys(dmat, map, buf, buflen, flags);
823 if (map->pagesneeded != 0) {
824 error = _bus_dmamap_reserve_pages(dmat, map, flags);
830 sl = map->slist + map->sync_count - 1;
835 sgsize = MIN(buflen, dmat->common.maxsegsz);
836 if (map->pagesneeded != 0 &&
837 must_bounce(dmat, map, curaddr, sgsize)) {
839 * The attempt to split a physically continuous buffer
840 * seems very controversial, it's unclear whether we
841 * can do this in all cases. Also, memory for bounced
842 * buffers is allocated as pages, so we cannot
843 * guarantee multipage alignment.
845 KASSERT(dmat->common.alignment <= PAGE_SIZE,
846 ("bounced buffer cannot have alignment bigger "
847 "than PAGE_SIZE: %lu", dmat->common.alignment));
848 sgsize = MIN(sgsize, PAGE_SIZE - (curaddr & PAGE_MASK));
849 curaddr = add_bounce_page(dmat, map, 0, curaddr,
851 } else if ((map->flags & DMAMAP_COHERENT) == 0) {
852 if (map->sync_count > 0)
853 sl_end = sl->paddr + sl->datacount;
855 if (map->sync_count == 0 || curaddr != sl_end) {
856 if (++map->sync_count > dmat->common.nsegments)
861 sl->pages = PHYS_TO_VM_PAGE(curaddr);
862 KASSERT(sl->pages != NULL,
863 ("%s: page at PA:0x%08lx is not in "
864 "vm_page_array", __func__, curaddr));
865 sl->datacount = sgsize;
867 sl->datacount += sgsize;
869 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
881 bus_dmamap_unload(dmat, map);
882 return (EFBIG); /* XXX better return value here? */
888 * Utility function to load a linear buffer. segp contains
889 * the starting segment on entrace, and the ending segment on exit.
892 bounce_bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
893 bus_size_t buflen, pmap_t pmap, int flags, bus_dma_segment_t *segs,
896 struct sync_list *sl;
898 bus_addr_t curaddr, sl_pend;
899 vm_offset_t kvaddr, vaddr, sl_vend;
902 KASSERT((map->flags & DMAMAP_FROM_DMAMEM) != 0 ||
903 dmat->common.alignment <= PAGE_SIZE,
904 ("loading user buffer with alignment bigger than PAGE_SIZE is not "
908 segs = dmat->segments;
910 if (flags & BUS_DMA_LOAD_MBUF)
911 map->flags |= DMAMAP_MBUF;
913 if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
914 _bus_dmamap_count_pages(dmat, map, pmap, buf, buflen, flags);
915 if (map->pagesneeded != 0) {
916 error = _bus_dmamap_reserve_pages(dmat, map, flags);
923 * XXX Optimally we should parse input buffer for physically
924 * continuous segments first and then pass these segment into
927 sl = map->slist + map->sync_count - 1;
928 vaddr = (vm_offset_t)buf;
934 * Get the physical address for this segment.
936 if (__predict_true(pmap == kernel_pmap)) {
937 curaddr = pmap_kextract(vaddr);
940 curaddr = pmap_extract(pmap, vaddr);
945 * Compute the segment size, and adjust counts.
947 sgsize = MIN(buflen, dmat->common.maxsegsz);
948 if ((map->flags & DMAMAP_FROM_DMAMEM) == 0)
949 sgsize = MIN(sgsize, PAGE_SIZE - (curaddr & PAGE_MASK));
951 if (map->pagesneeded != 0 &&
952 must_bounce(dmat, map, curaddr, sgsize)) {
953 /* See comment in bounce_bus_dmamap_load_phys */
954 KASSERT(dmat->common.alignment <= PAGE_SIZE,
955 ("bounced buffer cannot have alignment bigger "
956 "than PAGE_SIZE: %lu", dmat->common.alignment));
957 curaddr = add_bounce_page(dmat, map, kvaddr, curaddr,
959 } else if ((map->flags & DMAMAP_COHERENT) == 0) {
960 if (map->sync_count > 0) {
961 sl_pend = sl->paddr + sl->datacount;
962 sl_vend = sl->vaddr + sl->datacount;
965 if (map->sync_count == 0 ||
966 (kvaddr != 0 && kvaddr != sl_vend) ||
967 (curaddr != sl_pend)) {
968 if (++map->sync_count > dmat->common.nsegments)
976 sl->pages = PHYS_TO_VM_PAGE(curaddr);
977 KASSERT(sl->pages != NULL,
978 ("%s: page at PA:0x%08lx is not "
979 "in vm_page_array", __func__,
982 sl->datacount = sgsize;
984 sl->datacount += sgsize;
986 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
998 bus_dmamap_unload(dmat, map);
999 return (EFBIG); /* XXX better return value here? */
1005 bounce_bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map,
1006 struct memdesc *mem, bus_dmamap_callback_t *callback, void *callback_arg)
1011 map->callback = callback;
1012 map->callback_arg = callback_arg;
1015 static bus_dma_segment_t *
1016 bounce_bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map,
1017 bus_dma_segment_t *segs, int nsegs, int error)
1021 segs = dmat->segments;
1026 * Release the mapping held by map.
1029 bounce_bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1031 struct bounce_page *bpage;
1033 while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1034 STAILQ_REMOVE_HEAD(&map->bpages, links);
1035 free_bounce_page(dmat, bpage);
1038 map->sync_count = 0;
1039 map->flags &= ~DMAMAP_MBUF;
1043 dma_preread_safe(vm_offset_t va, vm_size_t size)
1046 * Write back any partial cachelines immediately before and
1047 * after the DMA region.
1049 if (va & (dcache_line_size - 1))
1050 cpu_dcache_wb_range(va, 1);
1051 if ((va + size) & (dcache_line_size - 1))
1052 cpu_dcache_wb_range(va + size, 1);
1054 cpu_dcache_inv_range(va, size);
1058 dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op)
1060 uint32_t len, offset;
1063 vm_offset_t va, tempva;
1066 offset = sl->paddr & PAGE_MASK;
1068 size = sl->datacount;
1071 for ( ; size != 0; size -= len, pa += len, offset = 0, ++m) {
1073 if (sl->vaddr == 0) {
1074 len = min(PAGE_SIZE - offset, size);
1075 tempva = pmap_quick_enter_page(m);
1076 va = tempva | offset;
1077 KASSERT(pa == (VM_PAGE_TO_PHYS(m) | offset),
1078 ("unexpected vm_page_t phys: 0x%16lx != 0x%16lx",
1079 VM_PAGE_TO_PHYS(m) | offset, pa));
1081 len = sl->datacount;
1086 case BUS_DMASYNC_PREWRITE:
1087 case BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD:
1088 cpu_dcache_wb_range(va, len);
1090 case BUS_DMASYNC_PREREAD:
1092 * An mbuf may start in the middle of a cacheline. There
1093 * will be no cpu writes to the beginning of that line
1094 * (which contains the mbuf header) while dma is in
1095 * progress. Handle that case by doing a writeback of
1096 * just the first cacheline before invalidating the
1097 * overall buffer. Any mbuf in a chain may have this
1098 * misalignment. Buffers which are not mbufs bounce if
1099 * they are not aligned to a cacheline.
1101 dma_preread_safe(va, len);
1103 case BUS_DMASYNC_POSTREAD:
1104 case BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE:
1105 cpu_dcache_inv_range(va, len);
1108 panic("unsupported combination of sync operations: "
1113 pmap_quick_remove_page(tempva);
1118 bounce_bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map,
1119 bus_dmasync_op_t op)
1121 struct bounce_page *bpage;
1122 struct sync_list *sl, *end;
1123 vm_offset_t datavaddr, tempvaddr;
1125 if (op == BUS_DMASYNC_POSTWRITE)
1128 if ((op & BUS_DMASYNC_POSTREAD) != 0) {
1130 * Wait for any DMA operations to complete before the bcopy.
1135 if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1136 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1137 "performing bounce", __func__, dmat, dmat->common.flags,
1140 if ((op & BUS_DMASYNC_PREWRITE) != 0) {
1141 while (bpage != NULL) {
1143 datavaddr = bpage->datavaddr;
1144 if (datavaddr == 0) {
1145 tempvaddr = pmap_quick_enter_page(
1147 datavaddr = tempvaddr | bpage->dataoffs;
1150 bcopy((void *)datavaddr,
1151 (void *)bpage->vaddr, bpage->datacount);
1153 pmap_quick_remove_page(tempvaddr);
1154 if ((map->flags & DMAMAP_COHERENT) == 0)
1155 cpu_dcache_wb_range(bpage->vaddr,
1157 bpage = STAILQ_NEXT(bpage, links);
1159 dmat->bounce_zone->total_bounced++;
1160 } else if ((op & BUS_DMASYNC_PREREAD) != 0) {
1161 while (bpage != NULL) {
1162 if ((map->flags & DMAMAP_COHERENT) == 0)
1163 cpu_dcache_wbinv_range(bpage->vaddr,
1165 bpage = STAILQ_NEXT(bpage, links);
1169 if ((op & BUS_DMASYNC_POSTREAD) != 0) {
1170 while (bpage != NULL) {
1171 if ((map->flags & DMAMAP_COHERENT) == 0)
1172 cpu_dcache_inv_range(bpage->vaddr,
1175 datavaddr = bpage->datavaddr;
1176 if (datavaddr == 0) {
1177 tempvaddr = pmap_quick_enter_page(
1179 datavaddr = tempvaddr | bpage->dataoffs;
1182 bcopy((void *)bpage->vaddr,
1183 (void *)datavaddr, bpage->datacount);
1186 pmap_quick_remove_page(tempvaddr);
1187 bpage = STAILQ_NEXT(bpage, links);
1189 dmat->bounce_zone->total_bounced++;
1194 * Cache maintenance for normal (non-COHERENT non-bounce) buffers.
1196 if (map->sync_count != 0) {
1197 sl = &map->slist[0];
1198 end = &map->slist[map->sync_count];
1199 CTR3(KTR_BUSDMA, "%s: tag %p op 0x%x "
1200 "performing sync", __func__, dmat, op);
1202 for ( ; sl != end; ++sl)
1203 dma_dcache_sync(sl, op);
1206 if ((op & (BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE)) != 0) {
1208 * Wait for the bcopy to complete before any DMA operations.
1215 init_bounce_pages(void *dummy __unused)
1219 STAILQ_INIT(&bounce_zone_list);
1220 STAILQ_INIT(&bounce_map_waitinglist);
1221 STAILQ_INIT(&bounce_map_callbacklist);
1222 mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
1224 SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
1226 static struct sysctl_ctx_list *
1227 busdma_sysctl_tree(struct bounce_zone *bz)
1230 return (&bz->sysctl_tree);
1233 static struct sysctl_oid *
1234 busdma_sysctl_tree_top(struct bounce_zone *bz)
1237 return (bz->sysctl_tree_top);
1241 alloc_bounce_zone(bus_dma_tag_t dmat)
1243 struct bounce_zone *bz;
1245 /* Check to see if we already have a suitable zone */
1246 STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1247 if ((dmat->common.alignment <= bz->alignment) &&
1248 (dmat->common.lowaddr >= bz->lowaddr)) {
1249 dmat->bounce_zone = bz;
1254 if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_DEVBUF,
1255 M_NOWAIT | M_ZERO)) == NULL)
1258 STAILQ_INIT(&bz->bounce_page_list);
1259 bz->free_bpages = 0;
1260 bz->reserved_bpages = 0;
1261 bz->active_bpages = 0;
1262 bz->lowaddr = dmat->common.lowaddr;
1263 bz->alignment = MAX(dmat->common.alignment, PAGE_SIZE);
1265 snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1267 snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1268 STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1269 dmat->bounce_zone = bz;
1271 sysctl_ctx_init(&bz->sysctl_tree);
1272 bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
1273 SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1274 CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
1275 if (bz->sysctl_tree_top == NULL) {
1276 sysctl_ctx_free(&bz->sysctl_tree);
1277 return (0); /* XXX error code? */
1280 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1281 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1282 "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1283 "Total bounce pages");
1284 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1285 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1286 "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1287 "Free bounce pages");
1288 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1289 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1290 "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1291 "Reserved bounce pages");
1292 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1293 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1294 "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1295 "Active bounce pages");
1296 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1297 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1298 "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1299 "Total bounce requests");
1300 SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1301 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1302 "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1303 "Total bounce requests that were deferred");
1304 SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1305 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1306 "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1307 SYSCTL_ADD_UAUTO(busdma_sysctl_tree(bz),
1308 SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1309 "alignment", CTLFLAG_RD, &bz->alignment, "");
1315 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1317 struct bounce_zone *bz;
1320 bz = dmat->bounce_zone;
1322 while (numpages > 0) {
1323 struct bounce_page *bpage;
1325 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_DEVBUF,
1330 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
1331 M_NOWAIT, 0ul, bz->lowaddr, PAGE_SIZE, 0);
1332 if (bpage->vaddr == 0) {
1333 free(bpage, M_DEVBUF);
1336 bpage->busaddr = pmap_kextract(bpage->vaddr);
1337 mtx_lock(&bounce_lock);
1338 STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1342 mtx_unlock(&bounce_lock);
1350 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1352 struct bounce_zone *bz;
1355 mtx_assert(&bounce_lock, MA_OWNED);
1356 bz = dmat->bounce_zone;
1357 pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1358 if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1359 return (map->pagesneeded - (map->pagesreserved + pages));
1360 bz->free_bpages -= pages;
1361 bz->reserved_bpages += pages;
1362 map->pagesreserved += pages;
1363 pages = map->pagesneeded - map->pagesreserved;
1369 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1370 bus_addr_t addr, bus_size_t size)
1372 struct bounce_zone *bz;
1373 struct bounce_page *bpage;
1375 KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1377 bz = dmat->bounce_zone;
1378 if (map->pagesneeded == 0)
1379 panic("add_bounce_page: map doesn't need any pages");
1382 if (map->pagesreserved == 0)
1383 panic("add_bounce_page: map doesn't need any pages");
1384 map->pagesreserved--;
1386 mtx_lock(&bounce_lock);
1387 bpage = STAILQ_FIRST(&bz->bounce_page_list);
1389 panic("add_bounce_page: free page list is empty");
1391 STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1392 bz->reserved_bpages--;
1393 bz->active_bpages++;
1394 mtx_unlock(&bounce_lock);
1396 if (dmat->common.flags & BUS_DMA_KEEP_PG_OFFSET) {
1397 /* Page offset needs to be preserved. */
1398 bpage->vaddr |= addr & PAGE_MASK;
1399 bpage->busaddr |= addr & PAGE_MASK;
1401 bpage->datavaddr = vaddr;
1402 bpage->datapage = PHYS_TO_VM_PAGE(addr);
1403 bpage->dataoffs = addr & PAGE_MASK;
1404 bpage->datacount = size;
1405 STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1406 return (bpage->busaddr);
1410 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1412 struct bus_dmamap *map;
1413 struct bounce_zone *bz;
1415 bz = dmat->bounce_zone;
1416 bpage->datavaddr = 0;
1417 bpage->datacount = 0;
1418 if (dmat->common.flags & BUS_DMA_KEEP_PG_OFFSET) {
1420 * Reset the bounce page to start at offset 0. Other uses
1421 * of this bounce page may need to store a full page of
1422 * data and/or assume it starts on a page boundary.
1424 bpage->vaddr &= ~PAGE_MASK;
1425 bpage->busaddr &= ~PAGE_MASK;
1428 mtx_lock(&bounce_lock);
1429 STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1431 bz->active_bpages--;
1432 if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1433 if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1434 STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1435 STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1437 busdma_swi_pending = 1;
1438 bz->total_deferred++;
1439 swi_sched(vm_ih, 0);
1442 mtx_unlock(&bounce_lock);
1449 struct bus_dmamap *map;
1451 mtx_lock(&bounce_lock);
1452 while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1453 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1454 mtx_unlock(&bounce_lock);
1456 (dmat->common.lockfunc)(dmat->common.lockfuncarg, BUS_DMA_LOCK);
1457 bus_dmamap_load_mem(map->dmat, map, &map->mem,
1458 map->callback, map->callback_arg, BUS_DMA_WAITOK);
1459 (dmat->common.lockfunc)(dmat->common.lockfuncarg,
1461 mtx_lock(&bounce_lock);
1463 mtx_unlock(&bounce_lock);
1466 struct bus_dma_impl bus_dma_bounce_impl = {
1467 .tag_create = bounce_bus_dma_tag_create,
1468 .tag_destroy = bounce_bus_dma_tag_destroy,
1469 .id_mapped = bounce_bus_dma_id_mapped,
1470 .map_create = bounce_bus_dmamap_create,
1471 .map_destroy = bounce_bus_dmamap_destroy,
1472 .mem_alloc = bounce_bus_dmamem_alloc,
1473 .mem_free = bounce_bus_dmamem_free,
1474 .load_phys = bounce_bus_dmamap_load_phys,
1475 .load_buffer = bounce_bus_dmamap_load_buffer,
1476 .load_ma = bus_dmamap_load_ma_triv,
1477 .map_waitok = bounce_bus_dmamap_waitok,
1478 .map_complete = bounce_bus_dmamap_complete,
1479 .map_unload = bounce_bus_dmamap_unload,
1480 .map_sync = bounce_bus_dmamap_sync