kernel - Add description to static token initializers
[dragonfly.git] / sys / platform / pc32 / i386 / busdma_machdep.c
1 /*
2  * Copyright (c) 1997, 1998 Justin T. Gibbs.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions, and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. The name of the author may not be used to endorse or promote products
12  *    derived from this software without specific prior written permission.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
18  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/i386/i386/busdma_machdep.c,v 1.94 2008/08/15 20:51:31 kmacy Exp $
27  * $DragonFly: src/sys/platform/pc32/i386/busdma_machdep.c,v 1.23 2008/06/05 18:06:32 swildner Exp $
28  */
29
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/malloc.h>
33 #include <sys/mbuf.h>
34 #include <sys/uio.h>
35 #include <sys/bus_dma.h>
36 #include <sys/kernel.h>
37 #include <sys/sysctl.h>
38 #include <sys/lock.h>
39
40 #include <sys/thread2.h>
41 #include <sys/spinlock2.h>
42 #include <sys/mplock2.h>
43
44 #include <vm/vm.h>
45 #include <vm/vm_page.h>
46
47 /* XXX needed for to access pmap to convert per-proc virtual to physical */
48 #include <sys/proc.h>
49 #include <sys/lock.h>
50 #include <vm/vm_map.h>
51
52 #include <machine/md_var.h>
53
54 #define MAX_BPAGES      1024
55
56 /*
57  * 16 x N declared on stack.
58  */
59 #define BUS_DMA_CACHE_SEGMENTS  8
60
61 struct bounce_zone;
62 struct bus_dmamap;
63
64 struct bus_dma_tag {
65         bus_dma_tag_t   parent;
66         bus_size_t      alignment;
67         bus_size_t      boundary;
68         bus_addr_t      lowaddr;
69         bus_addr_t      highaddr;
70         bus_dma_filter_t *filter;
71         void            *filterarg;
72         bus_size_t      maxsize;
73         u_int           nsegments;
74         bus_size_t      maxsegsz;
75         int             flags;
76         int             ref_count;
77         int             map_count;
78         bus_dma_segment_t *segments;
79         struct bounce_zone *bounce_zone;
80 #ifdef SMP
81         struct spinlock spin;
82 #else
83         int             unused0;
84 #endif
85 };
86
87 /*
88  * bus_dma_tag private flags
89  */
90 #define BUS_DMA_BOUNCE_ALIGN    BUS_DMA_BUS2
91 #define BUS_DMA_BOUNCE_LOWADDR  BUS_DMA_BUS3
92 #define BUS_DMA_MIN_ALLOC_COMP  BUS_DMA_BUS4
93
94 #define BUS_DMA_COULD_BOUNCE    (BUS_DMA_BOUNCE_LOWADDR | BUS_DMA_BOUNCE_ALIGN)
95
96 #define BUS_DMAMEM_KMALLOC(dmat) \
97         ((dmat)->maxsize <= PAGE_SIZE && \
98          (dmat)->alignment <= PAGE_SIZE && \
99          (dmat)->lowaddr >= ptoa(Maxmem))
100
101 struct bounce_page {
102         vm_offset_t     vaddr;          /* kva of bounce buffer */
103         bus_addr_t      busaddr;        /* Physical address */
104         vm_offset_t     datavaddr;      /* kva of client data */
105         bus_size_t      datacount;      /* client data count */
106         STAILQ_ENTRY(bounce_page) links;
107 };
108
109 struct bounce_zone {
110         STAILQ_ENTRY(bounce_zone) links;
111         STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
112         STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
113 #ifdef SMP
114         struct spinlock spin;
115 #else
116         int             unused0;
117 #endif
118         int             total_bpages;
119         int             free_bpages;
120         int             reserved_bpages;
121         int             active_bpages;
122         int             total_bounced;
123         int             total_deferred;
124         int             reserve_failed;
125         bus_size_t      alignment;
126         bus_addr_t      lowaddr;
127         char            zoneid[8];
128         char            lowaddrid[20];
129         struct sysctl_ctx_list sysctl_ctx;
130         struct sysctl_oid *sysctl_tree;
131 };
132
133 #ifdef SMP
134 #define BZ_LOCK(bz)     spin_lock_wr(&(bz)->spin)
135 #define BZ_UNLOCK(bz)   spin_unlock_wr(&(bz)->spin)
136 #else
137 #define BZ_LOCK(bz)     crit_enter()
138 #define BZ_UNLOCK(bz)   crit_exit()
139 #endif
140
141 static struct lwkt_token bounce_zone_tok =
142         LWKT_TOKEN_MP_INITIALIZER(bounce_zone_tok);
143 static int busdma_zonecount;
144 static STAILQ_HEAD(, bounce_zone) bounce_zone_list =
145         STAILQ_HEAD_INITIALIZER(bounce_zone_list);
146
147 int busdma_swi_pending;
148 static int total_bounce_pages;
149 static int max_bounce_pages = MAX_BPAGES;
150 static int bounce_alignment = 1; /* XXX temporary */
151
152 TUNABLE_INT("hw.busdma.max_bpages", &max_bounce_pages);
153 TUNABLE_INT("hw.busdma.bounce_alignment", &bounce_alignment);
154
155 struct bus_dmamap {
156         struct bp_list  bpages;
157         int             pagesneeded;
158         int             pagesreserved;
159         bus_dma_tag_t   dmat;
160         void            *buf;           /* unmapped buffer pointer */
161         bus_size_t      buflen;         /* unmapped buffer length */
162         bus_dmamap_callback_t *callback;
163         void            *callback_arg;
164         STAILQ_ENTRY(bus_dmamap) links;
165 };
166
167 static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist =
168         STAILQ_HEAD_INITIALIZER(bounce_map_callbacklist);
169
170 static struct bus_dmamap nobounce_dmamap;
171
172 static int              alloc_bounce_zone(bus_dma_tag_t);
173 static int              alloc_bounce_pages(bus_dma_tag_t, u_int, int);
174 static int              reserve_bounce_pages(bus_dma_tag_t, bus_dmamap_t, int);
175 static void             return_bounce_pages(bus_dma_tag_t, bus_dmamap_t);
176 static bus_addr_t       add_bounce_page(bus_dma_tag_t, bus_dmamap_t,
177                             vm_offset_t, bus_size_t);
178 static void             free_bounce_page(bus_dma_tag_t, struct bounce_page *);
179
180 static bus_dmamap_t     get_map_waiting(bus_dma_tag_t);
181 static void             add_map_callback(bus_dmamap_t);
182
183 SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
184 SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bounce_pages,
185            0, "Total bounce pages");
186 SYSCTL_INT(_hw_busdma, OID_AUTO, max_bpages, CTLFLAG_RD, &max_bounce_pages,
187            0, "Max bounce pages per bounce zone");
188 SYSCTL_INT(_hw_busdma, OID_AUTO, bounce_alignment, CTLFLAG_RD,
189            &bounce_alignment, 0, "Obey alignment constraint");
190
191 static __inline int
192 run_filter(bus_dma_tag_t dmat, bus_addr_t paddr)
193 {
194         int retval;
195
196         retval = 0;
197         do {
198                 if (((paddr > dmat->lowaddr && paddr <= dmat->highaddr) ||
199                      (bounce_alignment && (paddr & (dmat->alignment - 1)) != 0))
200                  && (dmat->filter == NULL ||
201                      dmat->filter(dmat->filterarg, paddr) != 0))
202                         retval = 1;
203
204                 dmat = dmat->parent;
205         } while (retval == 0 && dmat != NULL);
206         return (retval);
207 }
208
209 static __inline
210 bus_dma_segment_t *
211 bus_dma_tag_lock(bus_dma_tag_t tag, bus_dma_segment_t *cache)
212 {
213         if (tag->nsegments <= BUS_DMA_CACHE_SEGMENTS)
214                 return(cache);
215 #ifdef SMP
216         spin_lock_wr(&tag->spin);
217 #endif
218         return(tag->segments);
219 }
220
221 static __inline
222 void
223 bus_dma_tag_unlock(bus_dma_tag_t tag)
224 {
225 #ifdef SMP
226         if (tag->nsegments > BUS_DMA_CACHE_SEGMENTS)
227                 spin_unlock_wr(&tag->spin);
228 #endif
229 }
230
231 /*
232  * Allocate a device specific dma_tag.
233  */
234 int
235 bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
236                    bus_size_t boundary, bus_addr_t lowaddr,
237                    bus_addr_t highaddr, bus_dma_filter_t *filter,
238                    void *filterarg, bus_size_t maxsize, int nsegments,
239                    bus_size_t maxsegsz, int flags, bus_dma_tag_t *dmat)
240 {
241         bus_dma_tag_t newtag;
242         int error = 0;
243
244         /*
245          * Sanity checks
246          */
247
248         if (alignment == 0)
249                 alignment = 1;
250         if (alignment & (alignment - 1))
251                 panic("alignment must be power of 2\n");
252
253         if (boundary != 0) {
254                 if (boundary & (boundary - 1))
255                         panic("boundary must be power of 2\n");
256                 if (boundary < maxsegsz) {
257                         kprintf("boundary < maxsegsz:\n");
258                         print_backtrace(-1);
259                         maxsegsz = boundary;
260                 }
261         }
262
263         /* Return a NULL tag on failure */
264         *dmat = NULL;
265
266         newtag = kmalloc(sizeof(*newtag), M_DEVBUF, M_INTWAIT | M_ZERO);
267
268 #ifdef SMP
269         spin_init(&newtag->spin);
270 #endif
271         newtag->parent = parent;
272         newtag->alignment = alignment;
273         newtag->boundary = boundary;
274         newtag->lowaddr = trunc_page((vm_paddr_t)lowaddr) + (PAGE_SIZE - 1);
275         newtag->highaddr = trunc_page((vm_paddr_t)highaddr) + (PAGE_SIZE - 1);
276         newtag->filter = filter;
277         newtag->filterarg = filterarg;
278         newtag->maxsize = maxsize;
279         newtag->nsegments = nsegments;
280         newtag->maxsegsz = maxsegsz;
281         newtag->flags = flags;
282         newtag->ref_count = 1; /* Count ourself */
283         newtag->map_count = 0;
284         newtag->segments = NULL;
285         newtag->bounce_zone = NULL;
286
287         /* Take into account any restrictions imposed by our parent tag */
288         if (parent != NULL) {
289                 newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
290                 newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
291
292                 if (newtag->boundary == 0) {
293                         newtag->boundary = parent->boundary;
294                 } else if (parent->boundary != 0) {
295                         newtag->boundary = MIN(parent->boundary,
296                                                newtag->boundary);
297                 }
298
299 #ifdef notyet
300                 newtag->alignment = MAX(parent->alignment, newtag->alignment);
301 #endif
302
303                 if (newtag->filter == NULL) {
304                         /*
305                          * Short circuit looking at our parent directly
306                          * since we have encapsulated all of its information
307                          */
308                         newtag->filter = parent->filter;
309                         newtag->filterarg = parent->filterarg;
310                         newtag->parent = parent->parent;
311                 }
312                 if (newtag->parent != NULL)
313                         parent->ref_count++;
314         }
315
316         if (newtag->lowaddr < ptoa(Maxmem))
317                 newtag->flags |= BUS_DMA_BOUNCE_LOWADDR;
318         if (bounce_alignment && newtag->alignment > 1 &&
319             !(newtag->flags & BUS_DMA_ALIGNED))
320                 newtag->flags |= BUS_DMA_BOUNCE_ALIGN;
321
322         if ((newtag->flags & BUS_DMA_COULD_BOUNCE) &&
323             (flags & BUS_DMA_ALLOCNOW) != 0) {
324                 struct bounce_zone *bz;
325
326                 /* Must bounce */
327
328                 error = alloc_bounce_zone(newtag);
329                 if (error)
330                         goto back;
331                 bz = newtag->bounce_zone;
332
333                 if (ptoa(bz->total_bpages) < maxsize) {
334                         int pages;
335
336                         if (flags & BUS_DMA_ONEBPAGE) {
337                                 pages = 1;
338                         } else {
339                                 pages = atop(round_page(maxsize)) -
340                                         bz->total_bpages;
341                                 pages = MAX(pages, 1);
342                         }
343
344                         /* Add pages to our bounce pool */
345                         if (alloc_bounce_pages(newtag, pages, flags) < pages)
346                                 error = ENOMEM;
347
348                         /* Performed initial allocation */
349                         newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
350                 }
351         }
352 back:
353         if (error)
354                 kfree(newtag, M_DEVBUF);
355         else
356                 *dmat = newtag;
357         return error;
358 }
359
360 int
361 bus_dma_tag_destroy(bus_dma_tag_t dmat)
362 {
363         if (dmat != NULL) {
364                 if (dmat->map_count != 0)
365                         return (EBUSY);
366
367                 while (dmat != NULL) {
368                         bus_dma_tag_t parent;
369
370                         parent = dmat->parent;
371                         dmat->ref_count--;
372                         if (dmat->ref_count == 0) {
373                                 if (dmat->segments != NULL)
374                                         kfree(dmat->segments, M_DEVBUF);
375                                 kfree(dmat, M_DEVBUF);
376                                 /*
377                                  * Last reference count, so
378                                  * release our reference
379                                  * count on our parent.
380                                  */
381                                 dmat = parent;
382                         } else
383                                 dmat = NULL;
384                 }
385         }
386         return (0);
387 }
388
389 bus_size_t
390 bus_dma_tag_getmaxsize(bus_dma_tag_t tag)
391 {
392         return(tag->maxsize);
393 }
394
395 /*
396  * Allocate a handle for mapping from kva/uva/physical
397  * address space into bus device space.
398  */
399 int
400 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
401 {
402         int error;
403
404         error = 0;
405
406         if (dmat->segments == NULL) {
407                 KKASSERT(dmat->nsegments && dmat->nsegments < 16384);
408                 dmat->segments = kmalloc(sizeof(bus_dma_segment_t) * 
409                                         dmat->nsegments, M_DEVBUF, M_INTWAIT);
410         }
411
412         if (dmat->flags & BUS_DMA_COULD_BOUNCE) {
413                 struct bounce_zone *bz;
414                 int maxpages;
415
416                 /* Must bounce */
417
418                 if (dmat->bounce_zone == NULL) {
419                         error = alloc_bounce_zone(dmat);
420                         if (error)
421                                 return error;
422                 }
423                 bz = dmat->bounce_zone;
424
425                 *mapp = kmalloc(sizeof(**mapp), M_DEVBUF, M_INTWAIT | M_ZERO);
426
427                 /* Initialize the new map */
428                 STAILQ_INIT(&((*mapp)->bpages));
429
430                 /*
431                  * Attempt to add pages to our pool on a per-instance
432                  * basis up to a sane limit.
433                  */
434                 if (dmat->flags & BUS_DMA_BOUNCE_ALIGN) {
435                         maxpages = max_bounce_pages;
436                 } else {
437                         maxpages = MIN(max_bounce_pages,
438                                        Maxmem - atop(dmat->lowaddr));
439                 }
440                 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0
441                  || (dmat->map_count > 0
442                   && bz->total_bpages < maxpages)) {
443                         int pages;
444
445                         if (flags & BUS_DMA_ONEBPAGE) {
446                                 pages = 1;
447                         } else {
448                                 pages = atop(round_page(dmat->maxsize));
449                                 pages = MIN(maxpages - bz->total_bpages, pages);
450                                 pages = MAX(pages, 1);
451                         }
452                         if (alloc_bounce_pages(dmat, pages, flags) < pages)
453                                 error = ENOMEM;
454
455                         if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0) {
456                                 if (!error)
457                                         dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
458                         } else {
459                                 error = 0;
460                         }
461                 }
462         } else {
463                 *mapp = NULL;
464         }
465         if (!error)
466                 dmat->map_count++;
467         return error;
468 }
469
470 /*
471  * Destroy a handle for mapping from kva/uva/physical
472  * address space into bus device space.
473  */
474 int
475 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
476 {
477         if (map != NULL) {
478                 if (STAILQ_FIRST(&map->bpages) != NULL)
479                         return (EBUSY);
480                 kfree(map, M_DEVBUF);
481         }
482         dmat->map_count--;
483         return (0);
484 }
485
486 static __inline bus_size_t
487 check_kmalloc(bus_dma_tag_t dmat, const void *vaddr0, int verify)
488 {
489         bus_size_t maxsize = 0;
490         uintptr_t vaddr = (uintptr_t)vaddr0;
491
492         if ((vaddr ^ (vaddr + dmat->maxsize - 1)) & ~PAGE_MASK) {
493                 if (verify || bootverbose)
494                         kprintf("boundary check failed\n");
495                 if (verify)
496                         print_backtrace(-1); /* XXX panic */
497                 maxsize = dmat->maxsize;
498         }
499         if (vaddr & (dmat->alignment - 1)) {
500                 if (verify || bootverbose)
501                         kprintf("alignment check failed\n");
502                 if (verify)
503                         print_backtrace(-1); /* XXX panic */
504                 if (dmat->maxsize < dmat->alignment)
505                         maxsize = dmat->alignment;
506                 else
507                         maxsize = dmat->maxsize;
508         }
509         return maxsize;
510 }
511
512 /*
513  * Allocate a piece of memory that can be efficiently mapped into
514  * bus device space based on the constraints lited in the dma tag.
515  *
516  * mapp is degenerate.  By definition this allocation should not require
517  * bounce buffers so do not allocate a dma map.
518  */
519 int
520 bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
521                  bus_dmamap_t *mapp)
522 {
523         int mflags;
524
525         /* If we succeed, no mapping/bouncing will be required */
526         *mapp = NULL;
527
528         if (dmat->segments == NULL) {
529                 KKASSERT(dmat->nsegments < 16384);
530                 dmat->segments = kmalloc(sizeof(bus_dma_segment_t) * 
531                                         dmat->nsegments, M_DEVBUF, M_INTWAIT);
532         }
533
534         if (flags & BUS_DMA_NOWAIT)
535                 mflags = M_NOWAIT;
536         else
537                 mflags = M_WAITOK;
538         if (flags & BUS_DMA_ZERO)
539                 mflags |= M_ZERO;
540
541         if (BUS_DMAMEM_KMALLOC(dmat)) {
542                 bus_size_t maxsize;
543
544                 *vaddr = kmalloc(dmat->maxsize, M_DEVBUF, mflags);
545
546                 /*
547                  * XXX
548                  * Check whether the allocation
549                  * - crossed a page boundary
550                  * - was not aligned
551                  * Retry with power-of-2 alignment in the above cases.
552                  */
553                 maxsize = check_kmalloc(dmat, *vaddr, 0);
554                 if (maxsize) {
555                         size_t size;
556
557                         kfree(*vaddr, M_DEVBUF);
558                         /* XXX check for overflow? */
559                         for (size = 1; size <= maxsize; size <<= 1)
560                                 ;
561                         *vaddr = kmalloc(size, M_DEVBUF, mflags);
562                         check_kmalloc(dmat, *vaddr, 1);
563                 }
564         } else {
565                 /*
566                  * XXX Use Contigmalloc until it is merged into this facility
567                  *     and handles multi-seg allocations.  Nobody is doing
568                  *     multi-seg allocations yet though.
569                  */
570                 *vaddr = contigmalloc(dmat->maxsize, M_DEVBUF, mflags,
571                     0ul, dmat->lowaddr, dmat->alignment, dmat->boundary);
572         }
573         if (*vaddr == NULL)
574                 return (ENOMEM);
575         return (0);
576 }
577
578 /*
579  * Free a piece of memory and it's allociated dmamap, that was allocated
580  * via bus_dmamem_alloc.  Make the same choice for free/contigfree.
581  */
582 void
583 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
584 {
585         /*
586          * dmamem does not need to be bounced, so the map should be
587          * NULL
588          */
589         if (map != NULL)
590                 panic("bus_dmamem_free: Invalid map freed\n");
591         if (BUS_DMAMEM_KMALLOC(dmat))
592                 kfree(vaddr, M_DEVBUF);
593         else
594                 contigfree(vaddr, dmat->maxsize, M_DEVBUF);
595 }
596
597 static __inline vm_paddr_t
598 _bus_dma_extract(pmap_t pmap, vm_offset_t vaddr)
599 {
600         if (pmap)
601                 return pmap_extract(pmap, vaddr);
602         else
603                 return pmap_kextract(vaddr);
604 }
605
606 /*
607  * Utility function to load a linear buffer.  lastaddrp holds state
608  * between invocations (for multiple-buffer loads).  segp contains
609  * the segment following the starting one on entrace, and the ending
610  * segment on exit.  first indicates if this is the first invocation
611  * of this function.
612  */
613 static int
614 _bus_dmamap_load_buffer(bus_dma_tag_t dmat,
615                         bus_dmamap_t map,
616                         void *buf, bus_size_t buflen,
617                         bus_dma_segment_t *segments,
618                         int nsegments,
619                         pmap_t pmap,
620                         int flags,
621                         vm_paddr_t *lastpaddrp,
622                         int *segp,
623                         int first)
624 {
625         vm_offset_t vaddr;
626         vm_paddr_t paddr, nextpaddr;
627         bus_dma_segment_t *sg;
628         bus_addr_t bmask;
629         int seg, error = 0;
630
631         if (map == NULL)
632                 map = &nobounce_dmamap;
633
634 #ifdef INVARIANTS
635         if (dmat->flags & BUS_DMA_ALIGNED)
636                 KKASSERT(((uintptr_t)buf & (dmat->alignment - 1)) == 0);
637 #endif
638
639         /*
640          * If we are being called during a callback, pagesneeded will
641          * be non-zero, so we can avoid doing the work twice.
642          */
643         if ((dmat->flags & BUS_DMA_COULD_BOUNCE) &&
644             map != &nobounce_dmamap && map->pagesneeded == 0) {
645                 vm_offset_t vendaddr;
646
647                 /*
648                  * Count the number of bounce pages
649                  * needed in order to complete this transfer
650                  */
651                 vaddr = (vm_offset_t)buf;
652                 vendaddr = (vm_offset_t)buf + buflen;
653
654                 while (vaddr < vendaddr) {
655                         paddr = _bus_dma_extract(pmap, vaddr);
656                         if (run_filter(dmat, paddr) != 0)
657                                 map->pagesneeded++;
658                         vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
659                 }
660         }
661
662         /* Reserve Necessary Bounce Pages */
663         if (map->pagesneeded != 0) {
664                 struct bounce_zone *bz;
665
666                 bz = dmat->bounce_zone;
667                 BZ_LOCK(bz);
668                 if (flags & BUS_DMA_NOWAIT) {
669                         if (reserve_bounce_pages(dmat, map, 0) != 0) {
670                                 BZ_UNLOCK(bz);
671                                 error = ENOMEM;
672                                 goto free_bounce;
673                         }
674                 } else {
675                         if (reserve_bounce_pages(dmat, map, 1) != 0) {
676                                 /* Queue us for resources */
677                                 map->dmat = dmat;
678                                 map->buf = buf;
679                                 map->buflen = buflen;
680
681                                 STAILQ_INSERT_TAIL(
682                                     &dmat->bounce_zone->bounce_map_waitinglist,
683                                     map, links);
684                                 BZ_UNLOCK(bz);
685
686                                 return (EINPROGRESS);
687                         }
688                 }
689                 BZ_UNLOCK(bz);
690         }
691
692         KKASSERT(*segp >= 1 && *segp <= nsegments);
693         seg = *segp;
694         sg = &segments[seg - 1];
695
696         vaddr = (vm_offset_t)buf;
697         nextpaddr = *lastpaddrp;
698         bmask = ~(dmat->boundary - 1);  /* note: will be 0 if boundary is 0 */
699
700         /* force at least one segment */
701         do {
702                 bus_size_t size;
703
704                 /*
705                  * Per-page main loop
706                  */
707                 paddr = _bus_dma_extract(pmap, vaddr);
708                 size = PAGE_SIZE - (paddr & PAGE_MASK);
709                 if (size > buflen)
710                         size = buflen;
711                 if (map->pagesneeded != 0 && run_filter(dmat, paddr)) {
712                         /*
713                          * note: this paddr has the same in-page offset
714                          * as vaddr and thus the paddr above, so the
715                          * size does not have to be recalculated
716                          */
717                         paddr = add_bounce_page(dmat, map, vaddr, size);
718                 }
719
720                 /*
721                  * Fill in the bus_dma_segment
722                  */
723                 if (first) {
724                         sg->ds_addr = paddr;
725                         sg->ds_len = size;
726                         first = 0;
727                 } else if (paddr == nextpaddr) {
728                         sg->ds_len += size;
729                 } else {
730                         sg++;
731                         seg++;
732                         if (seg > nsegments)
733                                 break;
734                         sg->ds_addr = paddr;
735                         sg->ds_len = size;
736                 }
737                 nextpaddr = paddr + size;
738
739                 /*
740                  * Handle maxsegsz and boundary issues with a nested loop
741                  */
742                 for (;;) {
743                         bus_size_t tmpsize;
744
745                         /*
746                          * Limit to the boundary and maximum segment size
747                          */
748                         if (((nextpaddr - 1) ^ sg->ds_addr) & bmask) {
749                                 tmpsize = dmat->boundary -
750                                           (sg->ds_addr & ~bmask);
751                                 if (tmpsize > dmat->maxsegsz)
752                                         tmpsize = dmat->maxsegsz;
753                                 KKASSERT(tmpsize < sg->ds_len);
754                         } else if (sg->ds_len > dmat->maxsegsz) {
755                                 tmpsize = dmat->maxsegsz;
756                         } else {
757                                 break;
758                         }
759
760                         /*
761                          * Futz, split the data into a new segment.
762                          */
763                         if (seg >= nsegments)
764                                 goto fail;
765                         sg[1].ds_len = sg[0].ds_len - tmpsize;
766                         sg[1].ds_addr = sg[0].ds_addr + tmpsize;
767                         sg[0].ds_len = tmpsize;
768                         sg++;
769                         seg++;
770                 }
771
772                 /*
773                  * Adjust for loop
774                  */
775                 buflen -= size;
776                 vaddr += size;
777         } while (buflen > 0);
778 fail:
779         if (buflen != 0)
780                 error = EFBIG;
781
782         *segp = seg;
783         *lastpaddrp = nextpaddr;
784
785 free_bounce:
786         if (error && (dmat->flags & BUS_DMA_COULD_BOUNCE) &&
787             map != &nobounce_dmamap) {
788                 _bus_dmamap_unload(dmat, map);
789                 return_bounce_pages(dmat, map);
790         }
791         return error;
792 }
793
794 /*
795  * Map the buffer buf into bus space using the dmamap map.
796  */
797 int
798 bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
799                 bus_size_t buflen, bus_dmamap_callback_t *callback,
800                 void *callback_arg, int flags)
801 {
802         bus_dma_segment_t cache_segments[BUS_DMA_CACHE_SEGMENTS];
803         bus_dma_segment_t *segments;
804         vm_paddr_t lastaddr = 0;
805         int error, nsegs = 1;
806
807         if (map != NULL) {
808                 /*
809                  * XXX
810                  * Follow old semantics.  Once all of the callers are fixed,
811                  * we should get rid of these internal flag "adjustment".
812                  */
813                 flags &= ~BUS_DMA_NOWAIT;
814                 flags |= BUS_DMA_WAITOK;
815
816                 map->callback = callback;
817                 map->callback_arg = callback_arg;
818         }
819
820         segments = bus_dma_tag_lock(dmat, cache_segments);
821         error = _bus_dmamap_load_buffer(dmat, map, buf, buflen,
822                         segments, dmat->nsegments,
823                         NULL, flags, &lastaddr, &nsegs, 1);
824         if (error == EINPROGRESS) {
825                 bus_dma_tag_unlock(dmat);
826                 return error;
827         }
828         callback(callback_arg, segments, nsegs, error);
829         bus_dma_tag_unlock(dmat);
830         return 0;
831 }
832
833 /*
834  * Like _bus_dmamap_load(), but for mbufs.
835  */
836 int
837 bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map,
838                      struct mbuf *m0,
839                      bus_dmamap_callback2_t *callback, void *callback_arg,
840                      int flags)
841 {
842         bus_dma_segment_t cache_segments[BUS_DMA_CACHE_SEGMENTS];
843         bus_dma_segment_t *segments;
844         int nsegs, error;
845
846         /*
847          * XXX
848          * Follow old semantics.  Once all of the callers are fixed,
849          * we should get rid of these internal flag "adjustment".
850          */
851         flags &= ~BUS_DMA_WAITOK;
852         flags |= BUS_DMA_NOWAIT;
853
854         segments = bus_dma_tag_lock(dmat, cache_segments);
855         error = bus_dmamap_load_mbuf_segment(dmat, map, m0,
856                         segments, dmat->nsegments, &nsegs, flags);
857         if (error) {
858                 /* force "no valid mappings" in callback */
859                 callback(callback_arg, segments, 0,
860                          0, error);
861         } else {
862                 callback(callback_arg, segments, nsegs,
863                          m0->m_pkthdr.len, error);
864         }
865         bus_dma_tag_unlock(dmat);
866         return error;
867 }
868
869 int
870 bus_dmamap_load_mbuf_segment(bus_dma_tag_t dmat, bus_dmamap_t map,
871                              struct mbuf *m0,
872                              bus_dma_segment_t *segs, int maxsegs,
873                              int *nsegs, int flags)
874 {
875         int error;
876
877         M_ASSERTPKTHDR(m0);
878
879         KASSERT(maxsegs >= 1, ("invalid maxsegs %d\n", maxsegs));
880         KASSERT(maxsegs <= dmat->nsegments,
881                 ("%d too many segments, dmat only support %d segments\n",
882                  maxsegs, dmat->nsegments));
883         KASSERT(flags & BUS_DMA_NOWAIT,
884                 ("only BUS_DMA_NOWAIT is supported\n"));
885
886         if (m0->m_pkthdr.len <= dmat->maxsize) {
887                 int first = 1;
888                 vm_paddr_t lastaddr = 0;
889                 struct mbuf *m;
890
891                 *nsegs = 1;
892                 error = 0;
893                 for (m = m0; m != NULL && error == 0; m = m->m_next) {
894                         if (m->m_len == 0)
895                                 continue;
896
897                         error = _bus_dmamap_load_buffer(dmat, map,
898                                         m->m_data, m->m_len,
899                                         segs, maxsegs,
900                                         NULL, flags, &lastaddr,
901                                         nsegs, first);
902                         if (error == ENOMEM && !first) {
903                                 /*
904                                  * Out of bounce pages due to too many
905                                  * fragments in the mbuf chain; return
906                                  * EFBIG instead.
907                                  */
908                                 error = EFBIG;
909                         }
910                         first = 0;
911                 }
912 #ifdef INVARIANTS
913                 if (!error)
914                         KKASSERT(*nsegs <= maxsegs && *nsegs >= 1);
915 #endif
916         } else {
917                 *nsegs = 0;
918                 error = EINVAL;
919         }
920         KKASSERT(error != EINPROGRESS);
921         return error;
922 }
923
924 /*
925  * Like _bus_dmamap_load(), but for uios.
926  */
927 int
928 bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
929                     struct uio *uio,
930                     bus_dmamap_callback2_t *callback, void *callback_arg,
931                     int flags)
932 {
933         vm_paddr_t lastaddr;
934         int nsegs, error, first, i;
935         bus_size_t resid;
936         struct iovec *iov;
937         pmap_t pmap;
938         bus_dma_segment_t cache_segments[BUS_DMA_CACHE_SEGMENTS];
939         bus_dma_segment_t *segments;
940         bus_dma_segment_t *segs;
941         int nsegs_left;
942
943         if (dmat->nsegments <= BUS_DMA_CACHE_SEGMENTS)
944                 segments = cache_segments;
945         else
946                 segments = kmalloc(sizeof(bus_dma_segment_t) * dmat->nsegments,
947                                    M_DEVBUF, M_WAITOK | M_ZERO);
948
949         /*
950          * XXX
951          * Follow old semantics.  Once all of the callers are fixed,
952          * we should get rid of these internal flag "adjustment".
953          */
954         flags &= ~BUS_DMA_WAITOK;
955         flags |= BUS_DMA_NOWAIT;
956
957         resid = (bus_size_t)uio->uio_resid;
958         iov = uio->uio_iov;
959
960         segs = segments;
961         nsegs_left = dmat->nsegments;
962
963         if (uio->uio_segflg == UIO_USERSPACE) {
964                 struct thread *td;
965
966                 td = uio->uio_td;
967                 KASSERT(td != NULL && td->td_proc != NULL,
968                         ("bus_dmamap_load_uio: USERSPACE but no proc"));
969                 pmap = vmspace_pmap(td->td_proc->p_vmspace);
970         } else {
971                 pmap = NULL;
972         }
973
974         error = 0;
975         nsegs = 1;
976         first = 1;
977         lastaddr = 0;
978         for (i = 0; i < uio->uio_iovcnt && resid != 0 && !error; i++) {
979                 /*
980                  * Now at the first iovec to load.  Load each iovec
981                  * until we have exhausted the residual count.
982                  */
983                 bus_size_t minlen =
984                         resid < iov[i].iov_len ? resid : iov[i].iov_len;
985                 caddr_t addr = (caddr_t) iov[i].iov_base;
986
987                 error = _bus_dmamap_load_buffer(dmat, map, addr, minlen,
988                                 segs, nsegs_left,
989                                 pmap, flags, &lastaddr, &nsegs, first);
990                 first = 0;
991
992                 resid -= minlen;
993                 if (error == 0) {
994                         nsegs_left -= nsegs;
995                         segs += nsegs;
996                 }
997         }
998
999         /*
1000          * Minimum one DMA segment, even if 0-length buffer.
1001          */
1002         if (nsegs_left == dmat->nsegments)
1003                 --nsegs_left;
1004
1005         if (error) {
1006                 /* force "no valid mappings" in callback */
1007                 callback(callback_arg, segments, 0,
1008                          0, error);
1009         } else {
1010                 callback(callback_arg, segments, dmat->nsegments - nsegs_left,
1011                          (bus_size_t)uio->uio_resid, error);
1012         }
1013         if (dmat->nsegments > BUS_DMA_CACHE_SEGMENTS)
1014                 kfree(segments, M_DEVBUF);
1015         return error;
1016 }
1017
1018 /*
1019  * Release the mapping held by map.
1020  */
1021 void
1022 _bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1023 {
1024         struct bounce_page *bpage;
1025
1026         while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1027                 STAILQ_REMOVE_HEAD(&map->bpages, links);
1028                 free_bounce_page(dmat, bpage);
1029         }
1030 }
1031
1032 void
1033 _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1034 {
1035         struct bounce_page *bpage;
1036
1037         if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1038                 /*
1039                  * Handle data bouncing.  We might also
1040                  * want to add support for invalidating
1041                  * the caches on broken hardware
1042                  */
1043                 switch (op) {
1044                 case BUS_DMASYNC_PREWRITE:
1045                         while (bpage != NULL) {
1046                                 bcopy((void *)bpage->datavaddr,
1047                                       (void *)bpage->vaddr,
1048                                       bpage->datacount);
1049                                 bpage = STAILQ_NEXT(bpage, links);
1050                         }
1051                         dmat->bounce_zone->total_bounced++;
1052                         break;
1053
1054                 case BUS_DMASYNC_POSTREAD:
1055                         while (bpage != NULL) {
1056                                 bcopy((void *)bpage->vaddr,
1057                                       (void *)bpage->datavaddr,
1058                                       bpage->datacount);
1059                                 bpage = STAILQ_NEXT(bpage, links);
1060                         }
1061                         dmat->bounce_zone->total_bounced++;
1062                         break;
1063
1064                 case BUS_DMASYNC_PREREAD:
1065                 case BUS_DMASYNC_POSTWRITE:
1066                         /* No-ops */
1067                         break;
1068                 }
1069         }
1070 }
1071
1072 static int
1073 alloc_bounce_zone(bus_dma_tag_t dmat)
1074 {
1075         struct bounce_zone *bz, *new_bz;
1076
1077         KASSERT(dmat->bounce_zone == NULL,
1078                 ("bounce zone was already assigned\n"));
1079
1080         new_bz = kmalloc(sizeof(*new_bz), M_DEVBUF, M_INTWAIT | M_ZERO);
1081
1082         lwkt_gettoken(&bounce_zone_tok);
1083
1084         /* Check to see if we already have a suitable zone */
1085         STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1086                 if (dmat->alignment <= bz->alignment &&
1087                     dmat->lowaddr >= bz->lowaddr) {
1088                         lwkt_reltoken(&bounce_zone_tok);
1089
1090                         dmat->bounce_zone = bz;
1091                         kfree(new_bz, M_DEVBUF);
1092                         return 0;
1093                 }
1094         }
1095         bz = new_bz;
1096
1097 #ifdef SMP
1098         spin_init(&bz->spin);
1099 #endif
1100         STAILQ_INIT(&bz->bounce_page_list);
1101         STAILQ_INIT(&bz->bounce_map_waitinglist);
1102         bz->free_bpages = 0;
1103         bz->reserved_bpages = 0;
1104         bz->active_bpages = 0;
1105         bz->lowaddr = dmat->lowaddr;
1106         bz->alignment = round_page(dmat->alignment);
1107         ksnprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1108         busdma_zonecount++;
1109         ksnprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1110         STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1111
1112         lwkt_reltoken(&bounce_zone_tok);
1113
1114         dmat->bounce_zone = bz;
1115
1116         sysctl_ctx_init(&bz->sysctl_ctx);
1117         bz->sysctl_tree = SYSCTL_ADD_NODE(&bz->sysctl_ctx,
1118             SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1119             CTLFLAG_RD, 0, "");
1120         if (bz->sysctl_tree == NULL) {
1121                 sysctl_ctx_free(&bz->sysctl_ctx);
1122                 return 0;       /* XXX error code? */
1123         }
1124
1125         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1126             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1127             "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1128             "Total bounce pages");
1129         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1130             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1131             "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1132             "Free bounce pages");
1133         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1134             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1135             "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1136             "Reserved bounce pages");
1137         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1138             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1139             "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1140             "Active bounce pages");
1141         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1142             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1143             "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1144             "Total bounce requests");
1145         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1146             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1147             "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1148             "Total bounce requests that were deferred");
1149         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1150             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1151             "reserve_failed", CTLFLAG_RD, &bz->reserve_failed, 0,
1152             "Total bounce page reservations that were failed");
1153         SYSCTL_ADD_STRING(&bz->sysctl_ctx,
1154             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1155             "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1156         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1157             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1158             "alignment", CTLFLAG_RD, &bz->alignment, 0, "");
1159
1160         return 0;
1161 }
1162
1163 static int
1164 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages, int flags)
1165 {
1166         struct bounce_zone *bz = dmat->bounce_zone;
1167         int count = 0, mflags;
1168
1169         if (flags & BUS_DMA_NOWAIT)
1170                 mflags = M_NOWAIT;
1171         else
1172                 mflags = M_WAITOK;
1173
1174         while (numpages > 0) {
1175                 struct bounce_page *bpage;
1176
1177                 bpage = kmalloc(sizeof(*bpage), M_DEVBUF, M_INTWAIT | M_ZERO);
1178
1179                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
1180                                                          mflags, 0ul,
1181                                                          bz->lowaddr,
1182                                                          bz->alignment, 0);
1183                 if (bpage->vaddr == 0) {
1184                         kfree(bpage, M_DEVBUF);
1185                         break;
1186                 }
1187                 bpage->busaddr = pmap_kextract(bpage->vaddr);
1188
1189                 BZ_LOCK(bz);
1190                 STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1191                 total_bounce_pages++;
1192                 bz->total_bpages++;
1193                 bz->free_bpages++;
1194                 BZ_UNLOCK(bz);
1195
1196                 count++;
1197                 numpages--;
1198         }
1199         return count;
1200 }
1201
1202 /* Assume caller holds bounce zone spinlock */
1203 static int
1204 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1205 {
1206         struct bounce_zone *bz = dmat->bounce_zone;
1207         int pages;
1208
1209         pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1210         if (!commit && map->pagesneeded > (map->pagesreserved + pages)) {
1211                 bz->reserve_failed++;
1212                 return (map->pagesneeded - (map->pagesreserved + pages));
1213         }
1214
1215         bz->free_bpages -= pages;
1216
1217         bz->reserved_bpages += pages;
1218         KKASSERT(bz->reserved_bpages <= bz->total_bpages);
1219
1220         map->pagesreserved += pages;
1221         pages = map->pagesneeded - map->pagesreserved;
1222
1223         return pages;
1224 }
1225
1226 static void
1227 return_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map)
1228 {
1229         struct bounce_zone *bz = dmat->bounce_zone;
1230         int reserved = map->pagesreserved;
1231         bus_dmamap_t wait_map;
1232
1233         map->pagesreserved = 0;
1234         map->pagesneeded = 0;
1235
1236         if (reserved == 0)
1237                 return;
1238
1239         BZ_LOCK(bz);
1240
1241         bz->free_bpages += reserved;
1242         KKASSERT(bz->free_bpages <= bz->total_bpages);
1243
1244         KKASSERT(bz->reserved_bpages >= reserved);
1245         bz->reserved_bpages -= reserved;
1246
1247         wait_map = get_map_waiting(dmat);
1248
1249         BZ_UNLOCK(bz);
1250
1251         if (wait_map != NULL)
1252                 add_map_callback(map);
1253 }
1254
1255 static bus_addr_t
1256 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1257                 bus_size_t size)
1258 {
1259         struct bounce_zone *bz = dmat->bounce_zone;
1260         struct bounce_page *bpage;
1261
1262         KASSERT(map->pagesneeded > 0, ("map doesn't need any pages"));
1263         map->pagesneeded--;
1264
1265         KASSERT(map->pagesreserved > 0, ("map doesn't reserve any pages"));
1266         map->pagesreserved--;
1267
1268         BZ_LOCK(bz);
1269
1270         bpage = STAILQ_FIRST(&bz->bounce_page_list);
1271         KASSERT(bpage != NULL, ("free page list is empty"));
1272         STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1273
1274         KKASSERT(bz->reserved_bpages > 0);
1275         bz->reserved_bpages--;
1276
1277         bz->active_bpages++;
1278         KKASSERT(bz->active_bpages <= bz->total_bpages);
1279
1280         BZ_UNLOCK(bz);
1281
1282         bpage->datavaddr = vaddr;
1283         bpage->datacount = size;
1284         STAILQ_INSERT_TAIL(&map->bpages, bpage, links);
1285         return bpage->busaddr;
1286 }
1287
1288 static void
1289 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1290 {
1291         struct bounce_zone *bz = dmat->bounce_zone;
1292         bus_dmamap_t map;
1293
1294         bpage->datavaddr = 0;
1295         bpage->datacount = 0;
1296
1297         BZ_LOCK(bz);
1298
1299         STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1300
1301         bz->free_bpages++;
1302         KKASSERT(bz->free_bpages <= bz->total_bpages);
1303
1304         KKASSERT(bz->active_bpages > 0);
1305         bz->active_bpages--;
1306
1307         map = get_map_waiting(dmat);
1308
1309         BZ_UNLOCK(bz);
1310
1311         if (map != NULL)
1312                 add_map_callback(map);
1313 }
1314
1315 /* Assume caller holds bounce zone spinlock */
1316 static bus_dmamap_t
1317 get_map_waiting(bus_dma_tag_t dmat)
1318 {
1319         struct bounce_zone *bz = dmat->bounce_zone;
1320         bus_dmamap_t map;
1321
1322         map = STAILQ_FIRST(&bz->bounce_map_waitinglist);
1323         if (map != NULL) {
1324                 if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1325                         STAILQ_REMOVE_HEAD(&bz->bounce_map_waitinglist, links);
1326                         bz->total_deferred++;
1327                 } else {
1328                         map = NULL;
1329                 }
1330         }
1331         return map;
1332 }
1333
1334 static void
1335 add_map_callback(bus_dmamap_t map)
1336 {
1337         /* XXX callbacklist is not MPSAFE */
1338         crit_enter();
1339         get_mplock();
1340         STAILQ_INSERT_TAIL(&bounce_map_callbacklist, map, links);
1341         busdma_swi_pending = 1;
1342         setsoftvm();
1343         rel_mplock();
1344         crit_exit();
1345 }
1346
1347 void
1348 busdma_swi(void)
1349 {
1350         bus_dmamap_t map;
1351
1352         crit_enter();
1353         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1354                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1355                 crit_exit();
1356                 bus_dmamap_load(map->dmat, map, map->buf, map->buflen,
1357                                 map->callback, map->callback_arg, /*flags*/0);
1358                 crit_enter();
1359         }
1360         crit_exit();
1361 }