busdma(9): Dup i386 busdma_machdep.c to vkernel
authorSepherosa Ziehau <sephe@dragonflybsd.org>
Thu, 29 Jan 2009 11:25:37 +0000 (19:25 +0800)
committerSepherosa Ziehau <sephe@dragonflybsd.org>
Tue, 17 Feb 2009 10:35:50 +0000 (18:35 +0800)
sys/platform/vkernel/platform/busdma_machdep.c

index 3cdf4f9..0dc5983 100644 (file)
@@ -23,8 +23,8 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: src/sys/i386/i386/busdma_machdep.c,v 1.16.2.2 2003/01/23 00:55:27 scottl Exp $
- * $DragonFly: src/sys/platform/vkernel/platform/busdma_machdep.c,v 1.3 2008/06/06 13:19:25 swildner Exp $
+ * $FreeBSD: src/sys/i386/i386/busdma_machdep.c,v 1.94 2008/08/15 20:51:31 kmacy Exp $
+ * $DragonFly: src/sys/platform/pc32/i386/busdma_machdep.c,v 1.23 2008/06/05 18:06:32 swildner Exp $
  */
 
 #include <sys/param.h>
 #include <sys/uio.h>
 #include <sys/thread2.h>
 #include <sys/bus_dma.h>
+#include <sys/kernel.h>
+#include <sys/sysctl.h>
+#include <sys/lock.h>
+#include <sys/spinlock2.h>
 
 #include <vm/vm.h>
 #include <vm/vm_page.h>
 
 #include <machine/md_var.h>
 
-#define MAX_BPAGES 128
+#define MAX_BPAGES     1024
+
+struct bounce_zone;
+struct bus_dmamap;
 
 struct bus_dma_tag {
-       bus_dma_tag_t     parent;
-       bus_size_t        alignment;
-       bus_size_t        boundary;
-       bus_addr_t        lowaddr;
-       bus_addr_t        highaddr;
+       bus_dma_tag_t   parent;
+       bus_size_t      alignment;
+       bus_size_t      boundary;
+       bus_addr_t      lowaddr;
+       bus_addr_t      highaddr;
        bus_dma_filter_t *filter;
-       void             *filterarg;
-       bus_size_t        maxsize;
-       u_int             nsegments;
-       bus_size_t        maxsegsz;
-       int               flags;
-       int               ref_count;
-       int               map_count;
+       void            *filterarg;
+       bus_size_t      maxsize;
+       u_int           nsegments;
+       bus_size_t      maxsegsz;
+       int             flags;
+       int             ref_count;
+       int             map_count;
        bus_dma_segment_t *segments;
+       struct bounce_zone *bounce_zone;
 };
 
+/*
+ * bus_dma_tag private flags
+ */
+#define BUS_DMA_BOUNCE_ALIGN   BUS_DMA_BUS2
+#define BUS_DMA_BOUNCE_LOWADDR BUS_DMA_BUS3
+#define BUS_DMA_MIN_ALLOC_COMP BUS_DMA_BUS4
+
+#define BUS_DMA_COULD_BOUNCE   (BUS_DMA_BOUNCE_LOWADDR | BUS_DMA_BOUNCE_ALIGN)
+
+#define BUS_DMAMEM_KMALLOC(dmat) \
+       ((dmat)->maxsize <= PAGE_SIZE && \
+        (dmat)->alignment <= PAGE_SIZE && \
+        (dmat)->lowaddr >= ptoa(Maxmem))
+
 struct bounce_page {
        vm_offset_t     vaddr;          /* kva of bounce buffer */
        bus_addr_t      busaddr;        /* Physical address */
@@ -72,37 +94,87 @@ struct bounce_page {
        STAILQ_ENTRY(bounce_page) links;
 };
 
+struct bounce_zone {
+       STAILQ_ENTRY(bounce_zone) links;
+       STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
+       STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
+#ifdef SMP
+       struct spinlock spin;
+#else
+       int             unused0;
+#endif
+       int             total_bpages;
+       int             free_bpages;
+       int             reserved_bpages;
+       int             active_bpages;
+       int             total_bounced;
+       int             total_deferred;
+       int             reserve_failed;
+       bus_size_t      alignment;
+       bus_addr_t      lowaddr;
+       char            zoneid[8];
+       char            lowaddrid[20];
+       struct sysctl_ctx_list sysctl_ctx;
+       struct sysctl_oid *sysctl_tree;
+};
+
+#ifdef SMP
+#define BZ_LOCK(bz)    spin_lock_wr(&(bz)->spin)
+#define BZ_UNLOCK(bz)  spin_unlock_wr(&(bz)->spin)
+#else
+#define BZ_LOCK(bz)    crit_enter()
+#define BZ_UNLOCK(bz)  crit_exit()
+#endif
+
+static struct lwkt_token bounce_zone_tok =
+       LWKT_TOKEN_INITIALIZER(bounce_zone_tok);
+static int busdma_zonecount;
+static STAILQ_HEAD(, bounce_zone) bounce_zone_list =
+       STAILQ_HEAD_INITIALIZER(bounce_zone_list);
+
 int busdma_swi_pending;
+static int total_bounce_pages;
+static int max_bounce_pages = MAX_BPAGES;
+static int bounce_alignment = 1; /* XXX temporary */
 
-static STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
-static int free_bpages;
-static int reserved_bpages;
-static int active_bpages;
-static int total_bpages;
-static bus_addr_t bounce_lowaddr = BUS_SPACE_MAXADDR;
+TUNABLE_INT("hw.busdma.max_bpages", &max_bounce_pages);
+TUNABLE_INT("hw.busdma.bounce_alignment", &bounce_alignment);
 
 struct bus_dmamap {
-       struct bp_list         bpages;
-       int                    pagesneeded;
-       int                    pagesreserved;
-       bus_dma_tag_t          dmat;
-       void                  *buf;             /* unmapped buffer pointer */
-       bus_size_t             buflen;          /* unmapped buffer length */
+       struct bp_list  bpages;
+       int             pagesneeded;
+       int             pagesreserved;
+       bus_dma_tag_t   dmat;
+       void            *buf;           /* unmapped buffer pointer */
+       bus_size_t      buflen;         /* unmapped buffer length */
        bus_dmamap_callback_t *callback;
-       void                  *callback_arg;
+       void            *callback_arg;
        STAILQ_ENTRY(bus_dmamap) links;
 };
 
-static STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
-static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist;
+static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist =
+       STAILQ_HEAD_INITIALIZER(bounce_map_callbacklist);
+
 static struct bus_dmamap nobounce_dmamap;
 
-static int alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages);
-static int reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map);
-static bus_addr_t add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map,
-                                  vm_offset_t vaddr, bus_size_t size);
-static void free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage);
-static __inline int run_filter(bus_dma_tag_t dmat, bus_addr_t paddr);
+static int             alloc_bounce_zone(bus_dma_tag_t);
+static int             alloc_bounce_pages(bus_dma_tag_t, u_int, int);
+static int             reserve_bounce_pages(bus_dma_tag_t, bus_dmamap_t, int);
+static void            return_bounce_pages(bus_dma_tag_t, bus_dmamap_t);
+static bus_addr_t      add_bounce_page(bus_dma_tag_t, bus_dmamap_t,
+                           vm_offset_t, bus_size_t);
+static void            free_bounce_page(bus_dma_tag_t, struct bounce_page *);
+
+static bus_dmamap_t    get_map_waiting(bus_dma_tag_t);
+static void            add_map_callback(bus_dmamap_t);
+
+SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
+SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bounce_pages,
+          0, "Total bounce pages");
+SYSCTL_INT(_hw_busdma, OID_AUTO, max_bpages, CTLFLAG_RD, &max_bounce_pages,
+          0, "Max bounce pages per bounce zone");
+SYSCTL_INT(_hw_busdma, OID_AUTO, bounce_alignment, CTLFLAG_RD,
+          &bounce_alignment, 0, "Obey alignment constraint");
 
 static __inline int
 run_filter(bus_dma_tag_t dmat, bus_addr_t paddr)
@@ -111,18 +183,17 @@ run_filter(bus_dma_tag_t dmat, bus_addr_t paddr)
 
        retval = 0;
        do {
-               if (paddr > dmat->lowaddr
-                && paddr <= dmat->highaddr
-                && (dmat->filter == NULL
-                 || (*dmat->filter)(dmat->filterarg, paddr) != 0))
+               if (((paddr > dmat->lowaddr && paddr <= dmat->highaddr) ||
+                    (bounce_alignment && (paddr & (dmat->alignment - 1)) != 0))
+                && (dmat->filter == NULL ||
+                    dmat->filter(dmat->filterarg, paddr) != 0))
                        retval = 1;
 
-               dmat = dmat->parent;            
+               dmat = dmat->parent;
        } while (retval == 0 && dmat != NULL);
        return (retval);
 }
 
-#define BUS_DMA_MIN_ALLOC_COMP BUS_DMA_BUS4
 /*
  * Allocate a device specific dma_tag.
  */
@@ -136,6 +207,25 @@ bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
        bus_dma_tag_t newtag;
        int error = 0;
 
+       /*
+        * Sanity checks
+        */
+
+       if (alignment == 0)
+               alignment = 1;
+       if (alignment & (alignment - 1))
+               panic("alignment must be power of 2\n");
+
+       if (boundary != 0) {
+               if (boundary & (boundary - 1))
+                       panic("boundary must be power of 2\n");
+               if (boundary < maxsegsz) {
+                       kprintf("boundary < maxsegsz:\n");
+                       backtrace();
+                       maxsegsz = boundary;
+               }
+       }
+
        /* Return a NULL tag on failure */
        *dmat = NULL;
 
@@ -155,16 +245,24 @@ bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
        newtag->ref_count = 1; /* Count ourself */
        newtag->map_count = 0;
        newtag->segments = NULL;
-       
+       newtag->bounce_zone = NULL;
+
        /* Take into account any restrictions imposed by our parent tag */
        if (parent != NULL) {
                newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
                newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
-               /*
-                * XXX Not really correct??? Probably need to honor boundary
-                *     all the way up the inheritence chain.
-                */
-               newtag->boundary = MAX(parent->boundary, newtag->boundary);
+
+               if (newtag->boundary == 0) {
+                       newtag->boundary = parent->boundary;
+               } else if (parent->boundary != 0) {
+                       newtag->boundary = MIN(parent->boundary,
+                                              newtag->boundary);
+               }
+
+#ifdef notyet
+               newtag->alignment = MAX(parent->alignment, newtag->alignment);
+#endif
+
                if (newtag->filter == NULL) {
                        /*
                         * Short circuit looking at our parent directly
@@ -174,49 +272,58 @@ bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
                        newtag->filterarg = parent->filterarg;
                        newtag->parent = parent->parent;
                }
-               if (newtag->parent != NULL) {
+               if (newtag->parent != NULL)
                        parent->ref_count++;
-               }
        }
-       
-       if (newtag->lowaddr < ptoa(Maxmem) &&
+
+       if (newtag->lowaddr < ptoa(Maxmem))
+               newtag->flags |= BUS_DMA_BOUNCE_LOWADDR;
+       if (bounce_alignment && newtag->alignment > 1 &&
+           !(newtag->flags & BUS_DMA_ALIGNED))
+               newtag->flags |= BUS_DMA_BOUNCE_ALIGN;
+
+       if ((newtag->flags & BUS_DMA_COULD_BOUNCE) &&
            (flags & BUS_DMA_ALLOCNOW) != 0) {
+               struct bounce_zone *bz;
+
                /* Must bounce */
 
-               if (lowaddr > bounce_lowaddr) {
-                       /*
-                        * Go through the pool and kill any pages
-                        * that don't reside below lowaddr.
-                        */
-                       panic("bus_dma_tag_create: page reallocation "
-                             "not implemented");
-               }
-               if (ptoa(total_bpages) < maxsize) {
+               error = alloc_bounce_zone(newtag);
+               if (error)
+                       goto back;
+               bz = newtag->bounce_zone;
+
+               if (ptoa(bz->total_bpages) < maxsize) {
                        int pages;
 
-                       pages = atop(maxsize) - total_bpages;
+                       if (flags & BUS_DMA_ONEBPAGE) {
+                               pages = 1;
+                       } else {
+                               pages = atop(round_page(maxsize)) -
+                                       bz->total_bpages;
+                               pages = MAX(pages, 1);
+                       }
 
                        /* Add pages to our bounce pool */
-                       if (alloc_bounce_pages(newtag, pages) < pages)
+                       if (alloc_bounce_pages(newtag, pages, flags) < pages)
                                error = ENOMEM;
+
+                       /* Performed initial allocation */
+                       newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
                }
-               /* Performed initial allocation */
-               newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
        }
-       
-       if (error != 0) {
+back:
+       if (error)
                kfree(newtag, M_DEVBUF);
-       } else {
+       else
                *dmat = newtag;
-       }
-       return (error);
+       return error;
 }
 
 int
 bus_dma_tag_destroy(bus_dma_tag_t dmat)
 {
        if (dmat != NULL) {
-
                if (dmat->map_count != 0)
                        return (EBUSY);
 
@@ -259,39 +366,51 @@ bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
                                        dmat->nsegments, M_DEVBUF, M_INTWAIT);
        }
 
-       if (dmat->lowaddr < ptoa(Maxmem)) {
-               /* Must bounce */
+       if (dmat->flags & BUS_DMA_COULD_BOUNCE) {
+               struct bounce_zone *bz;
                int maxpages;
 
+               /* Must bounce */
+
+               if (dmat->bounce_zone == NULL) {
+                       error = alloc_bounce_zone(dmat);
+                       if (error)
+                               return error;
+               }
+               bz = dmat->bounce_zone;
+
                *mapp = kmalloc(sizeof(**mapp), M_DEVBUF, M_INTWAIT | M_ZERO);
-               if (*mapp == NULL)
-                       return (ENOMEM);
+
                /* Initialize the new map */
                STAILQ_INIT(&((*mapp)->bpages));
+
                /*
                 * Attempt to add pages to our pool on a per-instance
                 * basis up to a sane limit.
                 */
-               maxpages = MIN(MAX_BPAGES, Maxmem - atop(dmat->lowaddr));
+               if (dmat->flags & BUS_DMA_BOUNCE_ALIGN) {
+                       maxpages = max_bounce_pages;
+               } else {
+                       maxpages = MIN(max_bounce_pages,
+                                      Maxmem - atop(dmat->lowaddr));
+               }
                if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0
                 || (dmat->map_count > 0
-                 && total_bpages < maxpages)) {
+                 && bz->total_bpages < maxpages)) {
                        int pages;
 
-                       if (dmat->lowaddr > bounce_lowaddr) {
-                               /*
-                                * Go through the pool and kill any pages
-                                * that don't reside below lowaddr.
-                                */
-                               panic("bus_dmamap_create: page reallocation "
-                                     "not implemented");
+                       if (flags & BUS_DMA_ONEBPAGE) {
+                               pages = 1;
+                       } else {
+                               pages = atop(round_page(dmat->maxsize));
+                               pages = MIN(maxpages - bz->total_bpages, pages);
+                               pages = MAX(pages, 1);
                        }
-                       pages = atop(dmat->maxsize);
-                       pages = MIN(maxpages - total_bpages, pages);
-                       error = alloc_bounce_pages(dmat, pages);
+                       if (alloc_bounce_pages(dmat, pages, flags) < pages)
+                               error = ENOMEM;
 
                        if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0) {
-                               if (error == 0)
+                               if (!error)
                                        dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
                        } else {
                                error = 0;
@@ -300,9 +419,9 @@ bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
        } else {
                *mapp = NULL;
        }
-       if (error == 0)
+       if (!error)
                dmat->map_count++;
-       return (error);
+       return error;
 }
 
 /*
@@ -321,6 +440,29 @@ bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
        return (0);
 }
 
+static __inline bus_size_t
+check_kmalloc(bus_dma_tag_t dmat, const void *vaddr0, int verify)
+{
+       bus_size_t maxsize = 0;
+       uintptr_t vaddr = (uintptr_t)vaddr0;
+
+       if ((vaddr ^ (vaddr + dmat->maxsize - 1)) & ~PAGE_MASK) {
+               kprintf("boundary check failed\n");
+               if (verify)
+                       backtrace(); /* XXX panic */
+               maxsize = dmat->maxsize;
+       }
+       if (vaddr & (dmat->alignment - 1)) {
+               kprintf("alignment check failed\n");
+               if (verify)
+                       backtrace(); /* XXX panic */
+               if (dmat->maxsize < dmat->alignment)
+                       maxsize = dmat->alignment;
+               else
+                       maxsize = dmat->maxsize;
+       }
+       return maxsize;
+}
 
 /*
  * Allocate a piece of memory that can be efficiently mapped into
@@ -330,10 +472,11 @@ bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
  * bounce buffers so do not allocate a dma map.
  */
 int
-bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
+bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
                 bus_dmamap_t *mapp)
 {
        int mflags;
+
        /* If we succeed, no mapping/bouncing will be required */
        *mapp = NULL;
 
@@ -350,21 +493,28 @@ bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
        if (flags & BUS_DMA_ZERO)
                mflags |= M_ZERO;
 
-       if ((dmat->maxsize <= PAGE_SIZE) &&
-           dmat->lowaddr >= ptoa(Maxmem)) {
+       if (BUS_DMAMEM_KMALLOC(dmat)) {
+               bus_size_t maxsize;
+
                *vaddr = kmalloc(dmat->maxsize, M_DEVBUF, mflags);
+
                /*
-                * XXX Check whether the allocation crossed a page boundary
-                * and retry with power-of-2 alignment in that case.
+                * XXX
+                * Check whether the allocation
+                * - crossed a page boundary
+                * - was not aligned
+                * Retry with power-of-2 alignment in the above cases.
                 */
-               if ((((intptr_t)*vaddr) & PAGE_MASK) !=
-                   (((intptr_t)*vaddr + dmat->maxsize) & PAGE_MASK)) {
+               maxsize = check_kmalloc(dmat, *vaddr, 0);
+               if (maxsize) {
                        size_t size;
+
                        kfree(*vaddr, M_DEVBUF);
                        /* XXX check for overflow? */
-                       for (size = 1; size <= dmat->maxsize; size <<= 1)
+                       for (size = 1; size <= maxsize; size <<= 1)
                                ;
                        *vaddr = kmalloc(size, M_DEVBUF, mflags);
+                       check_kmalloc(dmat, *vaddr, 1);
                }
        } else {
                /*
@@ -373,8 +523,7 @@ bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
                 *     multi-seg allocations yet though.
                 */
                *vaddr = contigmalloc(dmat->maxsize, M_DEVBUF, mflags,
-                   0ul, dmat->lowaddr, dmat->alignment? dmat->alignment : 1ul,
-                   dmat->boundary);
+                   0ul, dmat->lowaddr, dmat->alignment, dmat->boundary);
        }
        if (*vaddr == NULL)
                return (ENOMEM);
@@ -394,217 +543,241 @@ bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
         */
        if (map != NULL)
                panic("bus_dmamem_free: Invalid map freed\n");
-       if ((dmat->maxsize <= PAGE_SIZE) &&
-           dmat->lowaddr >= ptoa(Maxmem))
+       if (BUS_DMAMEM_KMALLOC(dmat))
                kfree(vaddr, M_DEVBUF);
        else
                contigfree(vaddr, dmat->maxsize, M_DEVBUF);
 }
 
-#define BUS_DMAMAP_NSEGS ((BUS_SPACE_MAXSIZE / PAGE_SIZE) + 1)
+static __inline vm_paddr_t
+_bus_dma_extract(pmap_t pmap, vm_offset_t vaddr)
+{
+       if (pmap)
+               return pmap_extract(pmap, vaddr);
+       else
+               return pmap_kextract(vaddr);
+}
 
 /*
- * Map the buffer buf into bus space using the dmamap map.
+ * Utility function to load a linear buffer.  lastaddrp holds state
+ * between invocations (for multiple-buffer loads).  segp contains
+ * the segment following the starting one on entrace, and the ending
+ * segment on exit.  first indicates if this is the first invocation
+ * of this function.
  */
-int
-bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
-               bus_size_t buflen, bus_dmamap_callback_t *callback,
-               void *callback_arg, int flags)
+static int
+_bus_dmamap_load_buffer(bus_dma_tag_t dmat,
+                       bus_dmamap_t map,
+                       void *buf, bus_size_t buflen,
+                       bus_dma_segment_t *segments,
+                       int nsegments,
+                       pmap_t pmap,
+                       int flags,
+                       vm_paddr_t *lastpaddrp,
+                       int *segp,
+                       int first)
 {
-       vm_offset_t             vaddr;
-       vm_paddr_t              paddr;
-       bus_dma_segment_t      *sg;
-       int                     seg;
-       int                     error;
-       vm_paddr_t              nextpaddr;
+       vm_offset_t vaddr;
+       vm_paddr_t paddr, nextpaddr;
+       bus_dma_segment_t *sg;
+       bus_addr_t bmask;
+       int seg, error = 0;
 
        if (map == NULL)
                map = &nobounce_dmamap;
 
-       error = 0;
+#ifdef INVARIANTS
+       if (dmat->flags & BUS_DMA_ALIGNED)
+               KKASSERT(((uintptr_t)buf & (dmat->alignment - 1)) == 0);
+#endif
+
        /*
         * If we are being called during a callback, pagesneeded will
         * be non-zero, so we can avoid doing the work twice.
         */
-       if (dmat->lowaddr < ptoa(Maxmem) &&
-           map->pagesneeded == 0) {
-               vm_offset_t     vendaddr;
+       if ((dmat->flags & BUS_DMA_COULD_BOUNCE) &&
+           map != &nobounce_dmamap && map->pagesneeded == 0) {
+               vm_offset_t vendaddr;
 
                /*
                 * Count the number of bounce pages
                 * needed in order to complete this transfer
                 */
-               vaddr = trunc_page((vm_offset_t)buf);
+               vaddr = (vm_offset_t)buf;
                vendaddr = (vm_offset_t)buf + buflen;
 
                while (vaddr < vendaddr) {
-                       paddr = pmap_kextract(vaddr);
-                       if (run_filter(dmat, paddr) != 0) {
-
+                       paddr = _bus_dma_extract(pmap, vaddr);
+                       if (run_filter(dmat, paddr) != 0)
                                map->pagesneeded++;
-                       }
-                       vaddr += PAGE_SIZE;
+                       vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
                }
        }
 
        /* Reserve Necessary Bounce Pages */
        if (map->pagesneeded != 0) {
-               crit_enter();
-               if (reserve_bounce_pages(dmat, map) != 0) {
-
-                       /* Queue us for resources */
-                       map->dmat = dmat;
-                       map->buf = buf;
-                       map->buflen = buflen;
-                       map->callback = callback;
-                       map->callback_arg = callback_arg;
+               struct bounce_zone *bz;
 
-                       STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
-                       crit_exit();
-
-                       return (EINPROGRESS);
+               bz = dmat->bounce_zone;
+               BZ_LOCK(bz);
+               if (flags & BUS_DMA_NOWAIT) {
+                       if (reserve_bounce_pages(dmat, map, 0) != 0) {
+                               BZ_UNLOCK(bz);
+                               error = ENOMEM;
+                               goto free_bounce;
+                       }
+               } else {
+                       if (reserve_bounce_pages(dmat, map, 1) != 0) {
+                               /* Queue us for resources */
+                               map->dmat = dmat;
+                               map->buf = buf;
+                               map->buflen = buflen;
+
+                               STAILQ_INSERT_TAIL(
+                                   &dmat->bounce_zone->bounce_map_waitinglist,
+                                   map, links);
+                               BZ_UNLOCK(bz);
+
+                               return (EINPROGRESS);
+                       }
                }
-               crit_exit();
+               BZ_UNLOCK(bz);
        }
 
+       KKASSERT(*segp >= 1 && *segp <= nsegments);
+       seg = *segp;
+       sg = &segments[seg - 1];
+
        vaddr = (vm_offset_t)buf;
-       sg = dmat->segments;
-       seg = 1;
-       sg->ds_len = 0;
+       nextpaddr = *lastpaddrp;
+       bmask = ~(dmat->boundary - 1);  /* note: will be 0 if boundary is 0 */
 
-       nextpaddr = 0;
+       /* force at least one segment */
        do {
-               bus_size_t      size;
+               bus_size_t size;
 
-               paddr = pmap_kextract(vaddr);
+               /*
+                * Per-page main loop
+                */
+               paddr = _bus_dma_extract(pmap, vaddr);
                size = PAGE_SIZE - (paddr & PAGE_MASK);
                if (size > buflen)
                        size = buflen;
-
                if (map->pagesneeded != 0 && run_filter(dmat, paddr)) {
+                       /*
+                        * note: this paddr has the same in-page offset
+                        * as vaddr and thus the paddr above, so the
+                        * size does not have to be recalculated
+                        */
                        paddr = add_bounce_page(dmat, map, vaddr, size);
                }
 
-               if (sg->ds_len == 0) {
+               /*
+                * Fill in the bus_dma_segment
+                */
+               if (first) {
                        sg->ds_addr = paddr;
                        sg->ds_len = size;
+                       first = 0;
                } else if (paddr == nextpaddr) {
                        sg->ds_len += size;
                } else {
-                       /* Go to the next segment */
                        sg++;
                        seg++;
-                       if (seg > dmat->nsegments)
+                       if (seg > nsegments)
                                break;
                        sg->ds_addr = paddr;
                        sg->ds_len = size;
                }
-               vaddr += size;
                nextpaddr = paddr + size;
+
+               /*
+                * Handle maxsegsz and boundary issues with a nested loop
+                */
+               for (;;) {
+                       bus_size_t tmpsize;
+
+                       /*
+                        * Limit to the boundary and maximum segment size
+                        */
+                       if (((nextpaddr - 1) ^ sg->ds_addr) & bmask) {
+                               tmpsize = dmat->boundary -
+                                         (sg->ds_addr & ~bmask);
+                               if (tmpsize > dmat->maxsegsz)
+                                       tmpsize = dmat->maxsegsz;
+                               KKASSERT(tmpsize < sg->ds_len);
+                       } else if (sg->ds_len > dmat->maxsegsz) {
+                               tmpsize = dmat->maxsegsz;
+                       } else {
+                               break;
+                       }
+
+                       /*
+                        * Futz, split the data into a new segment.
+                        */
+                       if (seg >= nsegments)
+                               goto fail;
+                       sg[1].ds_len = sg[0].ds_len - tmpsize;
+                       sg[1].ds_addr = sg[0].ds_addr + tmpsize;
+                       sg[0].ds_len = tmpsize;
+                       sg++;
+                       seg++;
+               }
+
+               /*
+                * Adjust for loop
+                */
                buflen -= size;
+               vaddr += size;
        } while (buflen > 0);
-
-       if (buflen != 0) {
-               kprintf("bus_dmamap_load: Too many segs! buf_len = 0x%lx\n",
-                      (u_long)buflen);
+fail:
+       if (buflen != 0)
                error = EFBIG;
-       }
 
-       (*callback)(callback_arg, dmat->segments, seg, error);
+       *segp = seg;
+       *lastpaddrp = nextpaddr;
 
-       return (0);
+free_bounce:
+       if (error && (dmat->flags & BUS_DMA_COULD_BOUNCE) &&
+           map != &nobounce_dmamap) {
+               _bus_dmamap_unload(dmat, map);
+               return_bounce_pages(dmat, map);
+       }
+       return error;
 }
 
 /*
- * Utility function to load a linear buffer.  lastaddrp holds state
- * between invocations (for multiple-buffer loads).  segp contains
- * the starting segment on entrace, and the ending segment on exit.
- * first indicates if this is the first invocation of this function.
+ * Map the buffer buf into bus space using the dmamap map.
  */
-static int
-_bus_dmamap_load_buffer(bus_dma_tag_t dmat,
-                       void *buf, bus_size_t buflen,
-                       struct thread *td,
-                       int flags,
-                       vm_offset_t *lastaddrp,
-                       int *segp,
-                       int first)
+int
+bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
+               bus_size_t buflen, bus_dmamap_callback_t *callback,
+               void *callback_arg, int flags)
 {
-       bus_dma_segment_t *segs;
-       bus_size_t sgsize;
-       bus_addr_t curaddr, lastaddr, baddr, bmask;
-       vm_offset_t vaddr = (vm_offset_t)buf;
-       int seg;
-       pmap_t pmap;
-
-       if (td->td_proc != NULL)
-               pmap = vmspace_pmap(td->td_proc->p_vmspace);
-       else
-               pmap = NULL;
-
-       segs = dmat->segments;
-       lastaddr = *lastaddrp;
-       bmask  = ~(dmat->boundary - 1);
-
-       for (seg = *segp; buflen > 0 ; ) {
-               /*
-                * Get the physical address for this segment.
-                */
-               if (pmap)
-                       curaddr = pmap_extract(pmap, vaddr);
-               else
-                       curaddr = pmap_kextract(vaddr);
-
-               /*
-                * Compute the segment size, and adjust counts.
-                */
-               sgsize = PAGE_SIZE - ((u_long)curaddr & PAGE_MASK);
-               if (buflen < sgsize)
-                       sgsize = buflen;
+       vm_paddr_t lastaddr = 0;
+       int error, nsegs = 1;
 
+       if (map != NULL) {
                /*
-                * Make sure we don't cross any boundaries.
+                * XXX
+                * Follow old semantics.  Once all of the callers are fixed,
+                * we should get rid of these internal flag "adjustment".
                 */
-               if (dmat->boundary > 0) {
-                       baddr = (curaddr + dmat->boundary) & bmask;
-                       if (sgsize > (baddr - curaddr))
-                               sgsize = (baddr - curaddr);
-               }
+               flags &= ~BUS_DMA_NOWAIT;
+               flags |= BUS_DMA_WAITOK;
 
-               /*
-                * Insert chunk into a segment, coalescing with
-                * previous segment if possible.
-                */
-               if (first) {
-                       segs[seg].ds_addr = curaddr;
-                       segs[seg].ds_len = sgsize;
-                       first = 0;
-               } else {
-                       if (curaddr == lastaddr &&
-                           (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
-                           (dmat->boundary == 0 ||
-                            (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
-                               segs[seg].ds_len += sgsize;
-                       else {
-                               if (++seg >= dmat->nsegments)
-                                       break;
-                               segs[seg].ds_addr = curaddr;
-                               segs[seg].ds_len = sgsize;
-                       }
-               }
-
-               lastaddr = curaddr + sgsize;
-               vaddr += sgsize;
-               buflen -= sgsize;
+               map->callback = callback;
+               map->callback_arg = callback_arg;
        }
 
-       *segp = seg;
-       *lastaddrp = lastaddr;
+       error = _bus_dmamap_load_buffer(dmat, map, buf, buflen,
+                       dmat->segments, dmat->nsegments,
+                       NULL, flags, &lastaddr, &nsegs, 1);
+       if (error == EINPROGRESS)
+               return error;
 
-       /*
-        * Did we fit?
-        */
-       return (buflen != 0 ? EFBIG : 0); /* XXX better return value here? */
+       callback(callback_arg, dmat->segments, nsegs, error);
+       return 0;
 }
 
 /*
@@ -618,39 +791,79 @@ bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map,
 {
        int nsegs, error;
 
-       KASSERT(dmat->lowaddr >= ptoa(Maxmem) || map != NULL,
-               ("bus_dmamap_load_mbuf: No support for bounce pages!"));
-       KASSERT(m0->m_flags & M_PKTHDR,
-               ("bus_dmamap_load_mbuf: no packet header"));
+       /*
+        * XXX
+        * Follow old semantics.  Once all of the callers are fixed,
+        * we should get rid of these internal flag "adjustment".
+        */
+       flags &= ~BUS_DMA_WAITOK;
+       flags |= BUS_DMA_NOWAIT;
+
+       error = bus_dmamap_load_mbuf_segment(dmat, map, m0,
+                       dmat->segments, dmat->nsegments, &nsegs, flags);
+       if (error) {
+               /* force "no valid mappings" in callback */
+               callback(callback_arg, dmat->segments, 0, 0, error);
+       } else {
+               callback(callback_arg, dmat->segments, nsegs,
+                        m0->m_pkthdr.len, error);
+       }
+       return error;
+}
+
+int
+bus_dmamap_load_mbuf_segment(bus_dma_tag_t dmat, bus_dmamap_t map,
+                            struct mbuf *m0,
+                            bus_dma_segment_t *segs, int maxsegs,
+                            int *nsegs, int flags)
+{
+       int error;
+
+       M_ASSERTPKTHDR(m0);
+
+       KASSERT(maxsegs >= 1, ("invalid maxsegs %d\n", maxsegs));
+       KASSERT(maxsegs <= dmat->nsegments,
+               ("%d too many segments, dmat only support %d segments\n",
+                maxsegs, dmat->nsegments));
+       KASSERT(flags & BUS_DMA_NOWAIT,
+               ("only BUS_DMA_NOWAIT is supported\n"));
 
-       nsegs = 0;
-       error = 0;
        if (m0->m_pkthdr.len <= dmat->maxsize) {
                int first = 1;
-               vm_offset_t lastaddr = 0;
+               vm_paddr_t lastaddr = 0;
                struct mbuf *m;
 
+               *nsegs = 1;
+               error = 0;
                for (m = m0; m != NULL && error == 0; m = m->m_next) {
-                       if ( m->m_len == 0 )
+                       if (m->m_len == 0)
                                continue;
-                       error = _bus_dmamap_load_buffer(dmat,
+
+                       error = _bus_dmamap_load_buffer(dmat, map,
                                        m->m_data, m->m_len,
-                                       curthread, flags, &lastaddr,
-                                       &nsegs, first);
+                                       segs, maxsegs,
+                                       NULL, flags, &lastaddr,
+                                       nsegs, first);
+                       if (error == ENOMEM && !first) {
+                               /*
+                                * Out of bounce pages due to too many
+                                * fragments in the mbuf chain; return
+                                * EFBIG instead.
+                                */
+                               error = EFBIG;
+                       }
                        first = 0;
                }
+#ifdef INVARIANTS
+               if (!error)
+                       KKASSERT(*nsegs <= maxsegs && *nsegs >= 1);
+#endif
        } else {
+               *nsegs = 0;
                error = EINVAL;
        }
-
-       if (error) {
-               /* force "no valid mappings" in callback */
-               (*callback)(callback_arg, dmat->segments, 0, 0, error);
-       } else {
-               (*callback)(callback_arg, dmat->segments,
-                           nsegs+1, m0->m_pkthdr.len, error);
-       }
-       return (error);
+       KKASSERT(error != EINPROGRESS);
+       return error;
 }
 
 /*
@@ -662,27 +875,38 @@ bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
                    bus_dmamap_callback2_t *callback, void *callback_arg,
                    int flags)
 {
-       vm_offset_t lastaddr;
+       vm_paddr_t lastaddr;
        int nsegs, error, first, i;
        bus_size_t resid;
        struct iovec *iov;
-       struct thread *td = NULL;
+       pmap_t pmap;
 
-       KASSERT(dmat->lowaddr >= ptoa(Maxmem) || map != NULL,
-               ("bus_dmamap_load_uio: No support for bounce pages!"));
+       /*
+        * XXX
+        * Follow old semantics.  Once all of the callers are fixed,
+        * we should get rid of these internal flag "adjustment".
+        */
+       flags &= ~BUS_DMA_WAITOK;
+       flags |= BUS_DMA_NOWAIT;
 
        resid = uio->uio_resid;
        iov = uio->uio_iov;
 
        if (uio->uio_segflg == UIO_USERSPACE) {
+               struct thread *td;
+
                td = uio->uio_td;
                KASSERT(td != NULL && td->td_proc != NULL,
                        ("bus_dmamap_load_uio: USERSPACE but no proc"));
+               pmap = vmspace_pmap(td->td_proc->p_vmspace);
+       } else {
+               pmap = NULL;
        }
 
-       nsegs = 0;
        error = 0;
+       nsegs = 1;
        first = 1;
+       lastaddr = 0;
        for (i = 0; i < uio->uio_iovcnt && resid != 0 && !error; i++) {
                /*
                 * Now at the first iovec to load.  Load each iovec
@@ -692,9 +916,9 @@ bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
                        resid < iov[i].iov_len ? resid : iov[i].iov_len;
                caddr_t addr = (caddr_t) iov[i].iov_base;
 
-               error = _bus_dmamap_load_buffer(dmat,
-                               addr, minlen,
-                               td, flags, &lastaddr, &nsegs, first);
+               error = _bus_dmamap_load_buffer(dmat, map, addr, minlen,
+                               dmat->segments, dmat->nsegments,
+                               pmap, flags, &lastaddr, &nsegs, first);
                first = 0;
 
                resid -= minlen;
@@ -702,12 +926,12 @@ bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
 
        if (error) {
                /* force "no valid mappings" in callback */
-               (*callback)(callback_arg, dmat->segments, 0, 0, error);
+               callback(callback_arg, dmat->segments, 0, 0, error);
        } else {
-               (*callback)(callback_arg, dmat->segments,
-                           nsegs+1, uio->uio_resid, error);
+               callback(callback_arg, dmat->segments, nsegs,
+                        uio->uio_resid, error);
        }
-       return (error);
+       return error;
 }
 
 /*
@@ -730,7 +954,6 @@ _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
        struct bounce_page *bpage;
 
        if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
-               
                /*
                 * Handle data bouncing.  We might also
                 * want to add support for invalidating
@@ -744,6 +967,7 @@ _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
                                      bpage->datacount);
                                bpage = STAILQ_NEXT(bpage, links);
                        }
+                       dmat->bounce_zone->total_bounced++;
                        break;
 
                case BUS_DMASYNC_POSTREAD:
@@ -753,7 +977,9 @@ _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
                                      bpage->datacount);
                                bpage = STAILQ_NEXT(bpage, links);
                        }
+                       dmat->bounce_zone->total_bounced++;
                        break;
+
                case BUS_DMASYNC_PREREAD:
                case BUS_DMASYNC_POSTWRITE:
                        /* No-ops */
@@ -763,123 +989,290 @@ _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
 }
 
 static int
-alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
+alloc_bounce_zone(bus_dma_tag_t dmat)
 {
-       int count;
+       struct bounce_zone *bz, *new_bz;
+       lwkt_tokref ref;
+
+       KASSERT(dmat->bounce_zone == NULL,
+               ("bounce zone was already assigned\n"));
+
+       new_bz = kmalloc(sizeof(*new_bz), M_DEVBUF, M_INTWAIT | M_ZERO);
 
-       count = 0;
-       if (total_bpages == 0) {
-               STAILQ_INIT(&bounce_page_list);
-               STAILQ_INIT(&bounce_map_waitinglist);
-               STAILQ_INIT(&bounce_map_callbacklist);
+       lwkt_gettoken(&ref, &bounce_zone_tok);
+
+       /* Check to see if we already have a suitable zone */
+       STAILQ_FOREACH(bz, &bounce_zone_list, links) {
+               if (dmat->alignment <= bz->alignment &&
+                   dmat->lowaddr >= bz->lowaddr) {
+                       lwkt_reltoken(&ref);
+
+                       dmat->bounce_zone = bz;
+                       kfree(new_bz, M_DEVBUF);
+                       return 0;
+               }
        }
-       
+       bz = new_bz;
+
+#ifdef SMP
+       spin_init(&bz->spin);
+#endif
+       STAILQ_INIT(&bz->bounce_page_list);
+       STAILQ_INIT(&bz->bounce_map_waitinglist);
+       bz->free_bpages = 0;
+       bz->reserved_bpages = 0;
+       bz->active_bpages = 0;
+       bz->lowaddr = dmat->lowaddr;
+       bz->alignment = round_page(dmat->alignment);
+       ksnprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
+       busdma_zonecount++;
+       ksnprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
+       STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
+
+       lwkt_reltoken(&ref);
+
+       dmat->bounce_zone = bz;
+
+       sysctl_ctx_init(&bz->sysctl_ctx);
+       bz->sysctl_tree = SYSCTL_ADD_NODE(&bz->sysctl_ctx,
+           SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
+           CTLFLAG_RD, 0, "");
+       if (bz->sysctl_tree == NULL) {
+               sysctl_ctx_free(&bz->sysctl_ctx);
+               return 0;       /* XXX error code? */
+       }
+
+       SYSCTL_ADD_INT(&bz->sysctl_ctx,
+           SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
+           "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
+           "Total bounce pages");
+       SYSCTL_ADD_INT(&bz->sysctl_ctx,
+           SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
+           "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
+           "Free bounce pages");
+       SYSCTL_ADD_INT(&bz->sysctl_ctx,
+           SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
+           "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
+           "Reserved bounce pages");
+       SYSCTL_ADD_INT(&bz->sysctl_ctx,
+           SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
+           "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
+           "Active bounce pages");
+       SYSCTL_ADD_INT(&bz->sysctl_ctx,
+           SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
+           "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
+           "Total bounce requests");
+       SYSCTL_ADD_INT(&bz->sysctl_ctx,
+           SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
+           "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
+           "Total bounce requests that were deferred");
+       SYSCTL_ADD_INT(&bz->sysctl_ctx,
+           SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
+           "reserve_failed", CTLFLAG_RD, &bz->reserve_failed, 0,
+           "Total bounce page reservations that were failed");
+       SYSCTL_ADD_STRING(&bz->sysctl_ctx,
+           SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
+           "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
+       SYSCTL_ADD_INT(&bz->sysctl_ctx,
+           SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
+           "alignment", CTLFLAG_RD, &bz->alignment, 0, "");
+
+       return 0;
+}
+
+static int
+alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages, int flags)
+{
+       struct bounce_zone *bz = dmat->bounce_zone;
+       int count = 0, mflags;
+
+       if (flags & BUS_DMA_NOWAIT)
+               mflags = M_NOWAIT;
+       else
+               mflags = M_WAITOK;
+
        while (numpages > 0) {
                struct bounce_page *bpage;
 
-               bpage = (struct bounce_page *)kmalloc(sizeof(*bpage), M_DEVBUF,
-                                                    M_INTWAIT | M_ZERO);
+               bpage = kmalloc(sizeof(*bpage), M_DEVBUF, M_INTWAIT | M_ZERO);
 
-               if (bpage == NULL)
-                       break;
                bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
-                                                        M_NOWAIT, 0ul,
-                                                        dmat->lowaddr,
-                                                        PAGE_SIZE,
-                                                        0);
+                                                        mflags, 0ul,
+                                                        bz->lowaddr,
+                                                        bz->alignment, 0);
                if (bpage->vaddr == 0) {
                        kfree(bpage, M_DEVBUF);
                        break;
                }
                bpage->busaddr = pmap_kextract(bpage->vaddr);
-               crit_enter();
-               STAILQ_INSERT_TAIL(&bounce_page_list, bpage, links);
-               total_bpages++;
-               free_bpages++;
-               crit_exit();
+
+               BZ_LOCK(bz);
+               STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
+               total_bounce_pages++;
+               bz->total_bpages++;
+               bz->free_bpages++;
+               BZ_UNLOCK(bz);
+
                count++;
                numpages--;
        }
-       return (count);
+       return count;
 }
 
+/* Assume caller holds bounce zone spinlock */
 static int
-reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map)
+reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
 {
+       struct bounce_zone *bz = dmat->bounce_zone;
        int pages;
 
-       pages = MIN(free_bpages, map->pagesneeded - map->pagesreserved);
-       free_bpages -= pages;
-       reserved_bpages += pages;
+       pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
+       if (!commit && map->pagesneeded > (map->pagesreserved + pages)) {
+               bz->reserve_failed++;
+               return (map->pagesneeded - (map->pagesreserved + pages));
+       }
+
+       bz->free_bpages -= pages;
+
+       bz->reserved_bpages += pages;
+       KKASSERT(bz->reserved_bpages <= bz->total_bpages);
+
        map->pagesreserved += pages;
        pages = map->pagesneeded - map->pagesreserved;
 
-       return (pages);
+       return pages;
+}
+
+static void
+return_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map)
+{
+       struct bounce_zone *bz = dmat->bounce_zone;
+       int reserved = map->pagesreserved;
+       bus_dmamap_t wait_map;
+
+       map->pagesreserved = 0;
+       map->pagesneeded = 0;
+
+       if (reserved == 0)
+               return;
+
+       BZ_LOCK(bz);
+
+       bz->free_bpages += reserved;
+       KKASSERT(bz->free_bpages <= bz->total_bpages);
+
+       KKASSERT(bz->reserved_bpages >= reserved);
+       bz->reserved_bpages -= reserved;
+
+       wait_map = get_map_waiting(dmat);
+
+       BZ_UNLOCK(bz);
+
+       if (wait_map != NULL)
+               add_map_callback(map);
 }
 
 static bus_addr_t
 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
                bus_size_t size)
 {
+       struct bounce_zone *bz = dmat->bounce_zone;
        struct bounce_page *bpage;
 
-       if (map->pagesneeded == 0)
-               panic("add_bounce_page: map doesn't need any pages");
+       KASSERT(map->pagesneeded > 0, ("map doesn't need any pages"));
        map->pagesneeded--;
 
-       if (map->pagesreserved == 0)
-               panic("add_bounce_page: map doesn't need any pages");
+       KASSERT(map->pagesreserved > 0, ("map doesn't reserve any pages"));
        map->pagesreserved--;
 
-       crit_enter();
-       bpage = STAILQ_FIRST(&bounce_page_list);
-       if (bpage == NULL)
-               panic("add_bounce_page: free page list is empty");
+       BZ_LOCK(bz);
 
-       STAILQ_REMOVE_HEAD(&bounce_page_list, links);
-       reserved_bpages--;
-       active_bpages++;
-       crit_exit();
+       bpage = STAILQ_FIRST(&bz->bounce_page_list);
+       KASSERT(bpage != NULL, ("free page list is empty"));
+       STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
+
+       KKASSERT(bz->reserved_bpages > 0);
+       bz->reserved_bpages--;
+
+       bz->active_bpages++;
+       KKASSERT(bz->active_bpages <= bz->total_bpages);
+
+       BZ_UNLOCK(bz);
 
        bpage->datavaddr = vaddr;
        bpage->datacount = size;
-       STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
-       return (bpage->busaddr);
+       STAILQ_INSERT_TAIL(&map->bpages, bpage, links);
+       return bpage->busaddr;
 }
 
 static void
 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
 {
-       struct bus_dmamap *map;
+       struct bounce_zone *bz = dmat->bounce_zone;
+       bus_dmamap_t map;
 
        bpage->datavaddr = 0;
        bpage->datacount = 0;
 
-       crit_enter();
-       STAILQ_INSERT_HEAD(&bounce_page_list, bpage, links);
-       free_bpages++;
-       active_bpages--;
-       if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
-               if (reserve_bounce_pages(map->dmat, map) == 0) {
-                       panic("free_bounce_pages: uncoded\n");
-#if 0
-                       STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
-                       STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
-                                          map, links);
-                       busdma_swi_pending = 1;
-                       setsoftvm();
-#endif
+       BZ_LOCK(bz);
+
+       STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
+
+       bz->free_bpages++;
+       KKASSERT(bz->free_bpages <= bz->total_bpages);
+
+       KKASSERT(bz->active_bpages > 0);
+       bz->active_bpages--;
+
+       map = get_map_waiting(dmat);
+
+       BZ_UNLOCK(bz);
+
+       if (map != NULL)
+               add_map_callback(map);
+}
+
+/* Assume caller holds bounce zone spinlock */
+static bus_dmamap_t
+get_map_waiting(bus_dma_tag_t dmat)
+{
+       struct bounce_zone *bz = dmat->bounce_zone;
+       bus_dmamap_t map;
+
+       map = STAILQ_FIRST(&bz->bounce_map_waitinglist);
+       if (map != NULL) {
+               if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
+                       STAILQ_REMOVE_HEAD(&bz->bounce_map_waitinglist, links);
+                       bz->total_deferred++;
+               } else {
+                       map = NULL;
                }
        }
-       crit_exit();
+       return map;
 }
 
-#if 0
+static void
+add_map_callback(bus_dmamap_t map)
+{
+#ifdef notyet
+       /* XXX callbacklist is not MPSAFE */
+       crit_enter();
+       get_mplock();
+       STAILQ_INSERT_TAIL(&bounce_map_callbacklist, map, links);
+       busdma_swi_pending = 1;
+       setsoftvm();
+       rel_mplock();
+       crit_exit();
+#else
+       panic("%s uncoded\n", __func__);
+#endif
+}
 
+#ifdef notyet
 void
 busdma_swi(void)
 {
-       struct bus_dmamap *map;
+       bus_dmamap_t map;
 
        crit_enter();
        while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
@@ -891,6 +1284,4 @@ busdma_swi(void)
        }
        crit_exit();
 }
-
 #endif
-