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